How To Programmatically Assign Products To Multiple Categories In Magento 2
Magento 2 store is designed in such a way that shoppers find their required product easily. If that’s not the case, they may fumble into your store among the thousands of products that you offer and ultimately abandon the store due to the confusion.
We definitely do not want that to happen and hence divide the products among various categories. Category help users easily browse among the products and decide the best suited among them.
If you offer products that belong to multiple categories, maintaining it manually for each product can be tiresome. For example, you offer a t-shirt for men, you assign that product to men’s category as well as to the t-shirts category.
For a large number of products, if you have to implement such functionality, I have posted this solution to programmatically assign products to multiple categories in Magento 2.
Let’s dive right in.
Method to programmatically assign products to multiple categories in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try { $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $objectManager->get('Magento\Framework\App\State')->setAreaCode('adminhtml'); $newCategoryIds = array('148','152'); // It should be category Ids $sku = 'tshirt'; // It should be Product SKU $categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface'); $categoryLinkRepository->assignProductToCategories($sku, $newCategoryIds); } catch (\Exception $e) { echo "<pre>"; print_r($e->getMessage()); echo "</pre>"; } |
That’s it. You canset product position in a category in Magento 2 as the product position value determines the order of products on the category page.
You can also programmatically set URL key of the category in Magento 2, in case you are importing products to your store in bulk and want to create SEO-friendly category pages.
Any doubts about the implementation? Please mention it in the Comments section below and I’d be happy to help.
Do share the solution with the Magento community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
Hi Sanjay,
I am using this method in one of my scripts and it was always working well.
However I have the issue now that sometimes categories are not assigned.
Have you ever had this issue and do you know what the reason could be?
No error is thrown.
———————————
try {
$categoryLinkRepository = $objMan->get(‘\Magento\Catalog\Api\CategoryLinkManagementInterface’);
$categoryLinkRepository->assignProductToCategories($sku, $newCategoryIds);
} catch (\Exception $e) {
error_log(‘—-> PRODUCT IMPORT – Category issue for sku: ‘.$sku.’ : ‘.$e->getMessage());
continue;
}
———————————
$newCategoryIds has 3 different IDs. All are existing. One is not being assigned.
The “continue” is there to avoid a complete stop of the import.
The categories that have this issue are sub-categories in the category tree. I wonder if this could be a reason..
Thanks for your help
Jerome
Hello Jeromy,
No, we have not faced such an issue but you can check by running the reindex command.
Thank You
Hello,
Can you provide a root script for the same function for Magento 1.9.x ?
Your help in this regard is highly appreciated.
Regards,
Hello Brian,
I will post the solution in the future.
Do subscribe to Meetanshi’s blog posts to get notified for the same.
Thank You