I am trying to programatically remove a product from a category but it isn't working.

I have tried:

  • Using $product->setCategoryIds($categoryIds); and then saving with $productRepository->save($product);
  • Removing the category using $this->categoryLinkRepository->deleteByIds($categoryId, $productSku);,
  • Using $categoryLinkManagement->assignProductToCategories($productSky, $categoryIds) (should remove categories not in the list)

I have also tried manually reindexing after every attempt, but with all of these methods the product still stays in the category I don't want it to be in.

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

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

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


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.

  • As I noted in my post that sadly does not work – Kaascroissant Dec 12 '18 at 14:31

Remove existing and assign new categories to existing product while updating it programmatically in magento 2

As linked to this topic above, you have to use the method with categoryLinkRepository after the $product->save() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.