Is there a way to prevent magento 2 from replacing / by - when I try to rewrite the URL Key for my products?
Is there a way to prevent magento 2 from replacing / by - when I try to rewrite the URL Key for my products?
I needed to the exactly the same. I have done it by creating an around plugin to the formatUrlKey() method in \Magento\Catalog\Model\Product\Url
[EDIT] The best approach is to enable just the characters you want, so we still remove special characters and spaces. I am adding the code to allow only / and _
Just create a file: app/code/YourVendorName/YourModule/Plugin/FormatUrlKeyPlugin.php
<?php
declare(strict_types=1);
namespace YourVendorName\YourModule\Plugin;
/**
* Class FormatUrlKeyPlugin
* @package YourVendorName\YourModule\Plugin
*/
class FormatUrlKeyPlugin
{
/**
* FormatUrlKeyPlugin constructor.
* @param Translit $translit
*/
public function __construct(\Magento\Framework\Filter\Translit $translit)
{
$this->translit = $translit;
}
/**
* Prevent Magento from replacing slashes in url_key
*
* @param \Magento\Catalog\Model\Product\Url $subject
* @param callable $proceed
* @param $str
* @return mixed
*/
public function aroundFormatUrlKey(\Magento\Catalog\Model\Product\Url $subject, callable $proceed, $str)
{
$str = preg_replace('#[^0-9a-z_/]+#i', '-', $this->translit->filter($str));
$str = strtolower($str);
$str = trim($str, '-');
return $str;
}
}
And add the plugin to the di.xml (create a new one if you don't have it at your module) app/code/YourVendorName/YourModule/etc/di.xml
<?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\Catalog\Model\Product\Url">
<plugin name="FormatUrlKeyPlugin" type="YourVendorName\YourModule\Plugin\FormatUrlKeyPlugin" sortOrder="1" disabled="false"/>
</type>
</config>