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.