Magento 2.1 URL Rewrite – How to Renew Category URL Rewrites

magento-2.1magento2url-rewrite

I cannot get Magento 2 to renew URL rewrites for categories. I was forced to clear url_rewrites table after some weird problems happened after importing categories and products.

Now I get something like catalog/category/view/s/regntoj/id/304/.

I have tried the following

  • Save the category manually (doesn't work)
  • Change URL key and/or "content" and save the category manually (doesn't work)
  • "Marketing" > "URL rewrites" and add a rewrite rule (works)

I have more than 200 categories so going to Marketing > URL rewrites and manually setup each category will take a long time.

Best Answer

I suggest you do this in a setup script.

First, you will need to get a collection of \Magento\Catalog\Model\Category. You can do this by injecting the classes into the setup script constructor. I won't go too much into detail for this.

Then you would need to get an instance of Magento\CatalogUrlRewrite\Model\Category\CurrentUrlRewritesRegenerator. There is no service contract that calls the model's method so you need to instantiate the class by injecting the Factory class in your constructor.

Then create a loop through your category collection and pass the object through CurrentUrlRewritesRegenerator->generate() function, like so:

// pseudo
    foreach ($categories as $category) {
        $urlRewritesRegenerator->generate($storeId, $category);
    }

Hope this helps.

Related Topic