Dedicated Magento 2 Blog

Assign and Remove Products from Category Programmatically in Magento 2

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.

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.

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.