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:
<?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>"; }
It is a Magento 2 Root Script.
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.
Do share the solution with the Magento community via social media.
Thank you.