Question

I have a category created in my store with name "New Arrivals"

I want to add all products to this category which are created in last 45 days. This category products should be updated everyday with new products and remove old products.

How can I achieve this?

Was it helpful?

Solution

You can use below code to assign products created in last 45 days to your category.

$categoryId = 41; // Your category Id
$category = Mage::getModel('catalog/category')->load($categoryId);
$category->setPostedProducts(array()); // Removes all old products added to your category
$category->save(); 
$now = Mage::getModel('core/date')->timestamp(time());
$dateStart = date('Y-m-d' . ' 00:00:00', strtotime('-45 days'));
$dateEnd = date('Y-m-d' . ' 23:59:59', $now);
$collection = Mage::getModel("catalog/product")->getCollection()->addAttributeToSelect("*")->addFieldToFilter('created_at', array(
    'from'     => $dateStart,
    'to'       => $dateEnd,
    'datetime' => true
));
$category = array($categoryId);
foreach($collection as $product){
    $category = array_merge($category,$product->getCategoryIds());
    $product->setCategoryIds($category);
    $product->save();
} 

Create a function with above code in it and use cron to run the same function everyday. It will remove all products from category and update with new products. Refer How to setup cron.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top