0

How can I programmatically change URL-key on product save?
I need url-key as a first brand and product name (/brand-productname)

1

If you add a plugin for the model \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator. You can change the url key at this place.

I tested the code below and that does what you seek:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator">
        <plugin name="product_urlkey_generator" type="Mbs\ProductUrlKey\Plugin\GeneratorUrlKey" />
    </type>
</config>

<?php

namespace Mbs\ProductUrlKey\Plugin;

class GeneratorUrlKey
{
    public function aroundGetUrlKey(
        \Magento\CatalogUrlRewrite\Model\ProductUrlPathGenerator $subject,
        callable $proceed,
        \Magento\Catalog\Model\Product $product
    ) {
        $brand = $this->getBrandProductName($product);

        if ($brand!= '') {
            $originalProductName = $product->getName();

            $product->setName($brand . ' '. $originalProductName);
            $product->setData('url_key', null);
            $result = $proceed($product);
            $product->setName($originalProductName);
        } else {
            $result = $proceed($product);
        }

        return $result;
    }

    private function getBrandProductName(\Magento\Catalog\Model\Product $product)
    {
        return $product->getAttributeText('brand');
    }
}

see full module: https://bitbucket.org/magstaging/producturlkey/src/master/

5
  • Hey @hervetribouilloy thanks but that works on new product save only. can you help I needed for an updated product also? the existing product I save with brand name but doesn't update URL-key – Akshay Kamble Jul 6 '20 at 14:24
  • if your product url key exists, when the product is updated the url key should not need to be modified? are you saying it is possible to change the url key and remove the brand? – Herve Tribouilloy Jul 6 '20 at 14:44
  • No, I want if the URL key exists and I change the brand name URL key must be updated to the changed brand name and product title it doesn't work with the above plugin. I want urlkey dynamically with the brand name @hervetribouilloy .. – Akshay Kamble Jul 6 '20 at 15:08
  • I have now updated the answer, thanks for your feedback – Herve Tribouilloy Jul 6 '20 at 15:48
  • it does work on my machine, apologies, can't do much more – Herve Tribouilloy Jul 6 '20 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.