2

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.

4 Answers 4

1
<?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.

1
  • As I noted in my post that sadly does not work Dec 12, 2018 at 14:31
0

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.

0

Make sure you clear cache and generated files.

rm -rf generated/*;

Also the cache files

bin/magento cache:flush

and try

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

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

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

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

If this does not work what error are you getting?

0

Try this,

    $collection = $observer->getEvent()->getCollection();

        if (!empty($collection)) {
            foreach ($collection as $k => $product) {
                $prdIdd = $product->getEntityId();

                //Your Custom Attribute
                $customAttribute = $product->getYourCustomAttribute();

                $product->getData(); // You will get collection

 //           if(your condition){
                $collection->removeItemByKey($k);
//            }
            }

        } else {
            return $collection;
        }

Hope this works for you. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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