2

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?

3
  • Please add more description, do you have a category and assign products to that category? Mar 23, 2017 at 11:26
  • I have a category called New arrivals but I need to assign all recent 45 days new products to that category dynamically. How is this possible?
    – Mesk
    Mar 23, 2017 at 13:37
  • Has it to be a category or can it be a CMS page with a custom product list? So there is no need for cron/observer.
    – sv3n
    May 12, 2017 at 13:29

1 Answer 1

6

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.

22
  • Thanks for the code. The product is assigned to the category in admin panel. But the product is not showing under that category in frontend. Why?
    – Mesk
    Mar 24, 2017 at 9:55
  • Try reindex and refresh cache. Also make sure your products' visibility is set to "Catalog, Search" and they are in stock. Mar 24, 2017 at 10:00
  • Ok thanks I will try this, Is it possible to assign this last 45 days new products in Cron job? How to add this in my custom module's Observer.php for Cron job?
    – Mesk
    Mar 24, 2017 at 12:53
  • 1
    Check updated answer. You can use this code in your observer function as it is. Mar 24, 2017 at 13:06
  • Thanks. I will try this. Can you please let me know how to get & filter the products which price are greater than 50000INR programmatically as like above?
    – Mesk
    Mar 24, 2017 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.