Magento 2 – Regenerate Url Rewrites
In Magento 2, there is no way for admin to regenerate URL rewrites, it’s done automatically behind the scenes when admin add/edit product or category. Magento 1 had an indexer to regenerate URL keys. However, it’s no longer available in Magento 2.
Recently, I have faced a major issue with URL rewrites. All products are imported by an import script and also all categories are created by this script. The problem which I’ve faced that all product URL rewrites are not created automatically. They are only created by saving every single category. Magento 2 does not automatically create rewrites. They are only computed if you do an action like save category. This makes sense if you create categories and products in the backend. If you import these things by code, you have to save all categories manually after each import.
A quite simple solution is to use a ready to run Magento 2 module which does exactly the work of a rewrite indexer. A programmer did that in his module magento2-regenurl on GitHub. You can call this regeneration by code or from the command line. A better solution is to do it by code in your own importer module. The regeneration is quite simple:
foreach($list as $product) {
if($store_id === Store::DEFAULT_STORE_ID)
$product->setStoreId($store_id);
$this->urlPersist->deleteByData([
UrlRewrite::ENTITY_ID => $product->getId(),
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::REDIRECT_TYPE => 0,
UrlRewrite::STORE_ID => $store_id
]);
try {
$this->urlPersist->replace(
$this->productUrlRewriteGenerator->generate($product)
);
} catch(\Exception $e) {
$out->writeln('Duplicated url for '. $product->getId() .'');
}
}
As you can see Magento 2 offers you a model for regenerate Url rewrites \Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator (productUrlRewriteGenerator) which you can inject into your model. This generated URL rewrite can be replaced by \Magento\UrlRewrite\Model\UrlPersistInterface (urlPersist). You can run this in a loop for all products after import or for each single product after a change.
You can find URL rewrites in url_rewrite table in your database. This is exactly the same as in Magento 1.
I recently found this Magento 2 Module on GitHub, which fixes all my problems. I can recommend it. You can simply regenerate all your URL rewrites for products and categories with the following command:
bin/magento ok:urlrewrites:regenerate
Hope that helps! Happy Coding !!!