6

I just want to remove all products from given category,

for that I have tried below code which works absolutely fine , But it takes to much time ,

So I just want some code which works faster than this

$category = Mage::getModel('catalog/category')->load($categoryId);
$productCollection = $category->getProductCollection();
foreach($productCollection as $product){   
    Mage::getSingleton('catalog/category_api')
         ->removeProduct($categoryId,$product->getId());
}
3
  • How can i remove products from selected category, actually the products assigned three categories, i need remove one category?
    – zus
    Commented Dec 12, 2017 at 7:35
  • @zus in this code Mage::getSingleton('catalog/category_api') ->removeProduct($categoryId,$productId); Commented Dec 12, 2017 at 7:45
  • My code : <?php require_once 'app/Mage.php'; Mage::getSingleton('catalog/category_api')->removeProduct('1','3'); ?>:: product id : 1, category id: 3, its not removing
    – zus
    Commented Dec 12, 2017 at 9:12

2 Answers 2

16
$category = Mage::getModel('catalog/category')->load(176);
$category->setPostedProducts(array());
$category->save();
3
  • Great answer from Guineas , Thank you Marius you save my time . I Will accept answer after 15 min Commented Dec 7, 2016 at 8:37
  • Alternative (maybe wrong) assumption: using unsetPostedProducts() ? Commented Dec 7, 2016 at 8:56
  • 4
    @RaphaelatDigitalPianism. There is no method unsetPostedProducts and it cannot be magically called. if you try with unsPostedProducts it will still not work because the category save method takes into account products only if data['posted_products'] is set. That's why it needs to be an empty array.
    – Marius
    Commented Dec 7, 2016 at 9:07
3

Another wayt,you can do instead of run code and run this two MySql queries and it will works:

delete from catalog_category_product where category_id = [Your_CATEGORY_Id];

delete from catalog_category_product_index where category_id = [Your_CATEGORY_Id];

Then you need run category product indexing from index management

2
  • Thanks for your answer but I have created a shell script and I want to this on everyday , So your solution good if I want to do only at once Commented Dec 7, 2016 at 8:57
  • How can i remove products assigned to multiple categories, i need to remove those categories not for all, eg: product A assigned cat1, cat2, cat3 i need to remove cat2. But cat1 and cat3 retain the same products.
    – zus
    Commented Dec 12, 2017 at 9:59

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.