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

How-to-configure-Tier-Price-in-Magento-2-programmatically
How to link products to categories in Magento 2 programmatically

* 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 addition 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.

At 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 leave a comment.

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

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