Magento Delete Products Programmatically


Magento Delete Products Programmatically : Some times we need to delete the products in magento. You can delete products programmatically from magento catalog. Before deleting products make sure you have set the store id because you can have multiple stores. In this example we are going to cover how to delete products programmatically in magento.


Magento Delete Products Programmatically

Here are the methods to delete products in magento –

Delete Single Product –

Magento Delete Products Programmatically:

<?php 
// Register a secure area
 Mage::register("isSecureArea", true); 

 $productId = 99; 
 try{   
 
 Mage::getModel("catalog/product")->load( $productId )->delete(); 
 
 }catch(Exception $e){
 echo $e->getMessage();
 } 
 ?>

The above method loads products & Deletes the product.

Magento Delete all Products Programmatically –

If you want to delete all the products. Create a new file at root and add the below lines of code which will delete all products one by one from magento.
1. Create a file at root – deleteProducts.php
2. Add the below code in this file.
3. Run this file as : www.yourdomain.com/deleteProducts.php

Magento Delete Products Programmatically:

<?php 
	set_time_limit(0);
	ini_set('memory_limit','512M');
	require_once './app/Mage.php';
    Mage :: app("default") -> setCurrentStore( Mage_Core_Model_App :: ADMIN_STORE_ID );
	$storeId = 1;
    $products = Mage :: getResourceModel('catalog/product_collection')->setStoreId($storeId)->getAllIds();
    if(is_array($products))
    {
        foreach ($products as $key => $productId)
        {
            try
            {
                $product = Mage::getModel('catalog/product')->load($productId)->delete();
                
            } 
            catch (Exception $e) 
            {
                Mage::log("Unable to delete product with ID: ". $productId .");
            }
        }
    }
  
 ?>

set_time_limit(0); & ini_set(‘memory_limit’,’512M’); is set to fix timeout and memory limit problems. The above example will delete all products from magento so be sure before running the above script.

Note : Before running the above script make sure you want to delete all products.

User Ans/Comments

📖 Read More


Advertisements