I want to remove the parent category from the subcategory URL.
For example, I would like to change:
www.magento2.com/Category1/Category2/gear/bags.html
to
www.magento2.com/bags.html
Is there any way to programmatically remove parent category from subcategory URL?
Best Answer
If you look at the class
Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator
which is responsible for the category URL rewrite generation, you will see that it uses a constant value to determine if the parent path should be added:The value is
which means the path is generated for every category that is not a top category (level 1 is the root category) and you cannot configure this value or turn off parent path generation.
And since it is a protected method we cannot modify the return value with a plugin. Instead you will have to write a plugin for the public method
getUrlPath()
that usesisNeedToGenerateUrlPathForParent()
.I would use an around plugin which does not call the original method, essentially replacing the method:
(this is the original method, but without the parent path generation)
Plugin documentation: http://devdocs.magento.com/guides/v2.1/extension-dev-guide/plugins.html
Update existing categories
This will apply for new categories. Unfortunately the category URLs are not generated by an indexer anymore, so reindexing does not change them and the only way to regenerate them is to save each category. It could be done with a one-off script that loads a collection of all categories and calls
save()
on it:Note that this is not optimized for performance at all and will load all categories at once. So if you have thousands of categories you might want to process them in batches.