How to Programmatically Set URL Key of Category in Magento 2
In this blog post, I will show you the complete method to programmatically set URL key of category in Magento 2.
Categorizing the products into different categories is imperative for businesses with a wide range of products on their shelves. Magento 2 (Adobe Commerce) allows store owners to create different categories and sub-categories for better organization of products in the stores.
The URL key or slug is the last part of the web address, which is easy to read and understand for the users. If you are a Magento 2 store owner, it is essential to make the URL key of the category pages SEO-friendly and optimized for a better user experience. By default, this can be done from the system configuration in the Magento backend (Read more). However, sometimes you may require a programmatic method for that.
In case you are integrating third-party services or product information management systems with your Magento 2 store, you may require a programmatic method to set the URL key of the category pages.
In this blog post, I will show you how to set Magento 2 category URL key programmatically.
Let’s begin.
Method to Programmatically Set URL Key of Magento 2 Category Page
You can set the URL key of category programmatically in Magento 2 using the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//categoryFactory is object of class MagentoCatalogModelCategoryFactory $categoryFactory = $this->categoryFactory->create(); $categoryFactory->setName("test); $categoryFactory->setCustomAttributes([ 'url_key' => "test-url", ]); try { $categoryFactory->save(); } catch (Exception $e) { echo $e->getMessage(); } |
That’s it!
I hope this solution will help you with setting Magento 2 category URL key programmatically.
In case you are facing any issues or have any doubts regarding the solution, feel free to ask. I would be happy to help you. 😇
Also, do not forget to share this Magento 2 solution with your developer friends via social media. 😊
Thanks for reading. 🍀
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
Prev
How to Back Up Shopify Store Manually & Using an App [2024]
10 Best Shopify Apps to Get More Traffic in 2024
Next