How to link products to categories in Magento 2 programmatically

Mai Xuan Truong

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 show you how to link products to categories in Magento 2 programmatically.

Adding Products to Category

To ensure that you have all the data needed for the code, you will have to get the category ID 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.

Removing Products from the 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. By leveraging our top-notch Magento 2 development services, you can enhance the appearance of your website and incorporate comprehensive Magento 2 capabilities without breaking the bank. If you have any questions or opinions, feel free to reach out to us today to revolutionize your website with this resilient Magento development.

Latest Insights

How to Start a Shopify Store in Just Over an Hour Course

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.