How to remove a product from a category magento 1.5

走远了吗. 提交于 2019-12-11 03:35:22

问题


I'm kind of new in Magento and I'm working on a cron job that removes a product in a specific category after the date that was assigned. With work and the help of Stackoverflow, I came up with this code:

require_once 'app/Mage.php';
Mage::app();
$date = Mage::getModel('core/date')->date('Y-m-d H:i:s');
$collection = Mage::getModel('catalog/product')->getCollection();    
$collection->addfieldtofilter('news_to_date', array(array('to' => $date)));        
foreach($collection as $product) {        
   $product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_DISABLED);
   $product->save();
 }

This checks the actual date and compares it with the date of the products. If the date has passed, the product is disabled. What I need is that instead of disabling the product, the code should remove the product of the category (in this case the category is 'Sales')

I hope you guys can help me!

Thanks in advance!


回答1:


You need get all category ids from product, then remove Sales category ID from category ids array and set them back to product.

Example, Sales category ID is 5.

foreach ($collection as $product) {
    //Getting all category ids
    $ids = $product->getCategoryIds();
    //Searching array key with value 5 and removing from array
    if (($key = array_search(5, $ids)) !== false) {
        unset($ids[$key]);
        $product->setCategoryIds($ids)
        $product->save();
    }
}

P.S. You can use magento cron job functionality, than you do not need to use:

require_once 'app/Mage.php';
Mage::app();


来源:https://stackoverflow.com/questions/17798615/how-to-remove-a-product-from-a-category-magento-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!