How can I programmatically change URL-key on product save?
I need url-key as a first brand and product name (/brand-productname)
1 Answer
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/
-
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 Commented Jul 6, 2020 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? Commented Jul 6, 2020 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 .. Commented Jul 6, 2020 at 15:08
-
I have now updated the answer, thanks for your feedback Commented Jul 6, 2020 at 15:48
-
it does work on my machine, apologies, can't do much more Commented Jul 6, 2020 at 17:04