Delete all products in a given category via php

MagentoI had to remove all the products assigned to a category that was used as trash bin for some reasons, the problem was that the amount of products was pretty massive (16000) and I had no chances to do it manually, so I made a small PHP script to do the job.


<?php
 require_once "app/Mage.php";
 Mage::app('admin');
 $category_id = 146;
 $products = Mage::getModel('catalog/product')->getCollection();
 foreach($products as $product){
  $categories = $product->getCategoryIds();
  if(in_array($category_id, $categories)) {
   $product_load = Mage::getSingleton('catalog/product')->load($product->getId());
   Mage::dispatchEvent('catalog_controller_product_delete', array('product' => $product_load));
   $product_load->delete();
  }
 }
?>

Enjoy!

14 thoughts on “Delete all products in a given category via php

  1. Pingback: How to Delete All Products Within a Category - Gomagento2

    • I’m not sure I got it right, but I think you are asking how to do it for multiple categories.

      You have several routes:

      1. Create an array with all the categories you need to clean and then loop on it with your favorite construct
      2. Run the piece of code multiple times with your selected category
      3. Automate the category cleanup process with bash scripts that feed the category
  2. Pingback: How to Delete All Products Within a Category - MagentoHub

  3. Pingback: How to Delete All Products Within a Category | DL-UAT

      • Hi Soraph,
        thank you for your quick reply.
        Is there a specific location where I need to place this file?
        Will it work on version 1.9.1?

  4. Thanks for script.
    I think you dont need load product, I replace this line :
    $product_load = Mage::getSingleton(‘catalog/product’)->load($product->getId());
    On a:
    $product_load = $product;
    And script works correctly, and dont make additional query

Leave a reply to Ulrich Cancel reply