Magento 2 stores provide categories in such a way that customers can find particular products easily. If products are not well categorized, then it is hard to find the needed product.
Customers will confuse among the thousands of products in your store and left your store without purchasing any product.
If you don’t want that to happen in your online store, It is important to categorize products into suitable categories.
So that customers can quickly browse needed products from categories and can choose the best product among them.
In this tutorial, we will show how to assign products to multiple categories in Magento 2.
You can assign your product to multiple categories from Magento 2 Admin Panel, but when there are multiple products then it will become hard.
So, you can also programmatically assign products to multiple categories in Magento 2. For that, follow the below code.
Create an Instance of \Magento\Catalog\Api\CategoryLinkManagementInterface in your code.
<?php protected $_categoryLinkRepository; public function __construct( \Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkRepository ){ $this->_categoryLinkRepository = $categoryLinkRepository; } public function assignCategory() { $newCategoryIds = array('44','55'); // your category id $sku = 'product-sku'; //SKU of product you want to assign multiple category $this->_categoryLinkRepository->assignProductToCategories($sku, $newCategoryIds); } |
That’s it.
After running this code, check your storefront Categories.
Conclusion:
We hope the above blog helps you to clearly understand How to programmatically assign products to multiple categories in Magento 2.
In case of any kind of problem with the above code implementation, you can contact us or let us know in the comment section.
Thank You!