magento

Magento 2.4. unique url_key

While switching from Shopware 6 to Magento 2.4 I had to create some article which basically are not variants but had the same name.  The standard configuration of Magento 2.4 will create an url_key based on the name (and category if you want to and store id ...) but you easily see that if we have two articles with the same name we would have some trouble.

The solution which I used to avoid this is to change the file ProductUrlPathGenerator.php which you can find here in your Magento directory  under /vendor/magento/module-catalog-url-rewrite/Model/

What I did is to add the SKU (the article number) to the url_key to have it unique.

     * Prepare url key for product
     *
     * @param Product $product
     * @return string
     */
    protected function prepareProductUrlKey(Product $product)
    {
        $urlKey = (string)$product->getUrlKey();
        $urlKey = trim(strtolower($urlKey));

        return $product->formatUrlKey($urlKey ?: $product->getName() . "-" . $product->getSku());
    }