How to Add Products to Multiple Categories Programmatically in Magento 2?
Today, we’re going to teach you guys how to add products to multiple categories programmatically in Magento 2.
When it comes to online shopping, it is important for store owners to design their stores in such a way that makes it seamless to find required products.
And if that’s not the case on your online store, customers will often get lost among hundreds of other products that you sell, which will ultimately lead potential customers to abandon your online store due to confusion.
If you don’t want that to happen on your online store, it is vital to divide your products among multiple categories, which help visitors easily browse through the products on your store and find the ones they need.
And in this tutorial, we will show you exactly how to add your products to multiple categories programmatically in your Magento 2 store.
Step-by-Step Process to Add Products to Multiple Categories Programmatically in Magento 2
Adding products to multiple categories is extremely easy.
All you have to do is copy the following code in the Magento 2 root script, and make the necessary changes into the code based on your specific Magento 2 store requirements
<?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>"; }
And that’s all there is to it!
Conclusion
We hope that you found this tutorial helpful.
If you have any questions, please ask them in the comments below.
And if you need our professional assistance, feel free to contact us at any time.