Tag Archives: programatically delete product from category in Magento

Magento remove product from category programatically

Create a file in root directory of project and paste below code on that file and run this file on browser.
Please take a DB backup before use it.




In below script we are checking New category product From Date and To Date. if any product does not meet the date range than product automatically removed from that category


error_reporting(E_ALL);
ini_set('display_errors', 1);
define('MAGENTO_ROOT', getcwd());
$mageFilename = '../app/Mage.php';
require_once $mageFilename;
Mage::init();
$newCatId = 147; //category Id those you want to check it.


$cat = Mage::getModel('catalog/product')->setId($newCatId);
$collection = Mage::getModel('catalog/product')->getCollection()
->addCategoryFilter($cat)
->addAttributeToSelect('*');
$collection->addAttributeToFilter('status', 1);
$collection->addFieldToFilter(array(array('attribute' => 'visibility', 'neq' => "1")));
$collection->addUrlRewrite($cat);
//$collection->getSelect()->order('rand()');
//$collection->getSelect()->limit(4);



//Subtract 1 Day from current date
$date = strtotime(date('Y-m-d'));
$newDateDay = date('Y-m-d', strtotime('-1 day', $date)) . ' ' . date('H:i:s'); 


if (count($collection) > 0):
    foreach ($collection as $item):
        if (($item->getNewsFromDate() != '' && $item->getNewsFromDate() < date('Y-m-d H:i:s'))
                && ($item->getNewsToDate() == '' or $item->getNewsToDate() >= $newDateDay)) {
		// put the code that you want to meet the requirement
            
        } else {
            //Remove product from that category	    
            Mage::getSingleton('catalog/category_api')
		->removeProduct($newCatId,$item->getId());  // First Parameter is Category Id and Second is Product Id
        }

    endforeach;
endif;

// Indexing of the category
$process = Mage::getModel('index/indexer')->getProcessByCode('catalog_category_product');
$process->reindexAll();