Assign and Remove Products from Category Programmatically in Magento 2

assign_remove_category_magento2

Magento 2 provide inbuilt functionality to assign and remove products from category under Magento 2 admin > Products > Categories section. But sometimes we need to assign and remove products from category programmatically. In this code snippet, we will see how to assign products to category programmatically and remove products from category programmatically.

Note: For the demonstrated purpose we have used Objectmanager.Codextblog never recommend the direct use of ObjectManager.One should always use a constructor method to instant an object.

Assign Products to Category programmatically

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');

$category_ids = array('101','102');
$sku = '24-MB01';

$CategoryLinkRepository->assignProductToCategories($sku, $category_ids);
?>

In this code snippet, we have passed two parameters the first parameter is SKU of product and second parameter is the array of categories to assignProductToCategories function. Please note this code snippet will remove the products from previously assigned categories and assign the products to newly passed categories. For example, SKU ’24-MB01′ is assigned to category ids 99 and 100. After running above code SKU ’24-MB01′ will be removed from category ids 99, 100 and assigned to 101, 102.

Web Hosting


Remove Products from Category programmatically

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');

$categoryId = 101;
$sku = '24-MB01';

$CategoryLinkRepository->deleteByIds($categoryId,$sku);
?>

In this code snippet, we have passed two parameters the first parameter is category id and the second parameter is SKU to deleteByIds function. Please note this code snippet will remove the products from only that particular category and not from all previously assigned categories. For example, SKU ’24-MB01′ is previously assigned to category 99,100 and 101. After running above code SKU ’24-MB01′ will be removed from category id 101 only.

If you liked this post, then please like us on Facebook and follow us on Twitter.

Want to ask a question or leave a comment?

Leave a Comment

(6 Comments)

  • Vicky

    This is not working, during product update trying to remove the previously assigned categories and assign with the new ones..getting the category doesn’t not contain the specific product error.

    When i debug this getting error because of the product position , in table it says 0 in position when if i try to print empty array in product_positions

  • Parag

    This code is not working. I have tried it in my module and when I try to update the product that time I want that old category will be removed and a new one will be added but this code does not remove the old categories. I have got the categories ids of old ones and add the delete code in the loop but nothing happens.

    • Chirag

      What’s your Magento version?

      • Parag

        Its 2.3.4

  • Chandan Patra

    How we can assign products to a new Category without breaking the previous category assigment in Magento 2?

    Thanks and regards

    • Chirag Dodia

      To preserve previous assign categories you first need to create an array of previously assigning category id along with a new category id

      $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
      $collection = $productCollectionFactory->create();
      $collection->setPageSize(50);
      
      $CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
      
      foreach ($collection as $product) {
          
          //previous category array
          $previous_category_ids = $product->getCategoryIds();
      
         //add new category id in previous category array
          $previous_category_id[] = 101;
      
          $CategoryLinkRepository->assignProductToCategories($product->getSku(), $previous_category_id);
      
      }
      
      
  • All the comments are goes into moderation before approval. Irrelevant comment with links directly goes to spam. Your email address will not be published.

    Was this post helpful? Please support Us!

    Follow us on twitter or Like us on facebook.

     


    To Avoid Spam Downloads, We Want Your Email

    We will send you download link right
    away. Please submit form below.
    SEND ME DOWNLOAD LINK
    Close

    Increase Your
    Magento 2
    Knowledge

    Get Weekly Tutorial
    to your Inbox
    Subscribe Me
    close-link
    Subscribe Here