How to link products to categories in Magento 2 programmatically

Magento 2 provides inbuilt functionality to assign and remove products from the category under Magento 2 admin > Products > Categories section. However, there are situations when we need to dynamically assign and remove products from a category. In this article we will show you how to link products to categories in Magento 2 programmatically

1. Adding products to category:

To ensure that you have all the data needed for the code, you will have to get the category ID that you want to add to the product and the product ID of that product.

For example, we will add any product to the “Wine” category after saving the product.

Note: You can get category ID from  Catalog > Categories

Adding products to category

* Step 1: Add an observer for the saving product event.

<event name="catalog_product_save_after">
       <observer name="save_category_data" instance="Magenest\Movie\Observer\AfterProductSave"/>
</event>

* Step 2: Create AfterProductSave observer with additional argument – inject the CategoryLinkManagementInterface:

protected $categoryLinkManagementInterface;
 
   public function __construct(
       ....
      \Magento\Catalog\Model\ProductFactory $productFactory,
       \Magento\Catalog\Api\CategoryLinkManagementInterface  $categoryLinkManagementInterface
   )
   {
       ...
       $this->categoryLinkManagementInterface = $categoryLinkManagementInterface;
   }

* Step 3: Add the product to the new category. 

Note: $categoryId = [42] is the array of category ID that we use for this example

public function execute(Observer $observer)
   {
       $data = $this->request->getParams();
       $id = $data['id'];
       $product = $this->productFactory->create()->load($id);
       $categoryId = [42];
       $categoryIds = array_unique(
           array_merge(
               $product->getCategoryIds(),
               $categoryId
    public function execute(Observer $observer)
   {
       $data = $this->request->getParams();
       $id = $data['id'];
       $product = $this->productFactory->create()->load($id);
       $categoryId = [42];
       $categoryIds = array_unique(
           array_merge(
               $product->getCategoryIds(),
               $categoryId
           )
       );
       $this->categoryLinkManagementInterface->assignProductToCategories(
           $product->getSku(),
           $categoryIds
       );
   }

assignProductToCategories() will replace the existing categories list – therefore we have to add our category to the existing list, before assigning this list to the product.

2. Removing products from category:

The preparation and first two steps are the same as assigning products to categories.

In step 3, you will still use assignProductToCategories() to remove the category that you don’t want by removing it from the $categoryId array after getting the old categories array from getCategoryIds() method. In this example, we will remove all the old categories which were assigned to the product.

public function execute(Observer $observer)
   {
       $data = $this->request->getParams();
       $id = $data['id'];
       $product = $this->productFactory->create()->load($id);
       $categoryId = [];
       if (!empty($categoryIds)) {
       $this->categoryLinkManagementInterface->assignProductToCategories(
           $product->getSku(),
           $categoryIds
       );
   }

If you want to remove only certain categories, remove them from the existing categories array, then assign the modified array to the product.

Conclusion

Above is the tutorial which can help you to add or remove products from the category programmatically. If you have any questions or opinions, feel free to contact to our experienced Magento team. We’re always ready to help.

Latest Insights

eCommerce Statistics 2022 and the Trends
you need to know

Don't want to miss out on our latest insights?
Subscribe to our newsletter.

EMAIL

Disclaimer: By clicking submit, you agree to share your information with us to receive news, announcements, and resources when they are available.