Delete products and category programmatically magento

This tutorial explains how to remove the products and categories from the magento backend pro grammatically. This code deletes all the products and categories from the magento backend.

If you want to delete all the products it is not easy to remove it one by one.The code below removes all the products and the categories programmatically.

Step by step explanation

  1. Establish database connection
  2. Remove the products
  3. Remove the Catgories

Connect to magento database

As the first establish database connection as shown below.

require_once '../app/Mage.php';
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID));

Remove the products using script

The removeAllProducts() function removes all the products from the magento database using the script.

function removeAllProducts(){
    $products = Mage :: getResourceModel('catalog/product_collection')->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)->getAllIds();
    if(is_array($products))
    {
        foreach ($products as $key => $productId)
        {
            try
            {
                Mage::getModel('catalog/product')->load($productId)->delete();
                echo 'Product Removed '.$productId .PHP_EOL;

            }
            catch (Exception $e)
            {
                echo 'Failed to Remove product '.$productId .PHP_EOL;
            }
        }
    }
}

Remove the categories

The removeAllCategories() function removes all the categories from the magento database using the script.

If you have any further queries please leave a reply.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*