Sunday, November 10, 2013

Remove the products from category products and update or map new product to category in magento programmatically

In some time you need to remove all the products from category or unset all products from category and add or update new product to category at that time you use below code for ex:- you need to run cron job which will run every day and get a product collection of sale attribute and map that products to that category
<?php
    set_time_limit(0); 
    define('MAGENTO', '..');
    require_once MAGENTO . '/app/Mage.php';
    Mage::app();

    //Load product model collecttion filtered by sale attribute
     $proCollection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSelect(array('entity_id'))
                        ->addAttributeToFilter('sale', '1');
                         
    
$writeConnection = Mage::getSingleton('core/resource')->getConnection('core_write');

        // Delete Existing Mapped product from Sale Category
        $catId=722;
        $delQuery = 'Delete from catalog_category_product where category_id ='.$catId;
        $writeConnection->query($delQuery);
        $category=Mage::getModel('catalog/category')->load($catId);
        $products = array();
        $category_products='';
        foreach ($proCollection as $product){
            if(!$category_products){
                $category_products=$product->getId().'=1&';
            }else{
                $category_products .=$product->getId().'=1&';            
            }        
        }
        //$data['category_products']='4867=1&4868;=1&4876;=1';
        parse_str($category_products, $products);    
        $category->setPostedProducts($products)->save();
        
    
        $process = Mage::getModel('index/indexer')->getProcessByCode('catalog_category_product');
        $process->reindexAll();
        
        echo 'successfully mapped the data<br>';
        exit;

?>
Download file setSale.php
http://www.magentocommerce.com/boards/viewthread/704216/

No comments:

Post a Comment