Question

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

Was it helpful?

Solution

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top