How could I order latests products in Magento?

I’m trying to show the latest products on my magento store.

What is a recent product? It is defined by two criteria:

  • created_at
  • news_from_date

I’d like to order my product indifferently between created_at & news_from_date, not one criteria first, and the second after.

Any ideas?

I already tried the following code:

->addAttributeToSort('created_at, news_from_date', 'desc')

OR

->addAttributeToSort('news_from_date', 'desc')
->addAttributeToSort('created_at', 'desc')

OR

->addAttributeToSort(array('created_at' => 'desc', 'news_from_date' => 'desc'))

OR

->addAttributeToSort(array('created_at', 'news_from_date'), 'desc'))

4 thoughts on “How could I order latests products in Magento?”

  1. There is no “OR” in SQL order clauses so you need to find a way to reduce the problem to a single column. The following is untested but should give you an idea.

    // Make sure the correct attributes are available with names we choose.
    $products->addAttributeToSelect('created_at, news_from_date');
    
    // Choose the LATEST date to sort as it is the most RECENT.
    $products->addOrder('MAX(created_at, news_from_date)', 'desc');
    

  2. You can order/sort latest products by both created_at and news_from_date attributes at a time.

    Here is the code to do so:-

    $todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
    
    $collection = Mage::getModel('catalog/product')
                    ->getCollection()                   
                    ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
                    ->addAttributeToFilter('news_to_date', array('or'=> array(
                        0 => array('date' => true, 'from' => $todayDate),
                        1 => array('is' => new Zend_Db_Expr('null')))
                    ), 'left')
                    ->addAttributeToSort('news_from_date', 'desc')
                    ->addAttributeToSort('created_at', 'desc');
    

    Thanks.

  3. I’d recommend using the news_from_date instead of the created date. This gives you the flexibility to create content ahead of time, but still appear in the correct order when you publish it.

  4. Better:

    $_productCollection = $this->getLoadedProductCollection()->clear()->addAttributeToSort('created_at', 'DESC')->setPageSize(4);
    

Leave a Reply

Your email address will not be published. Required fields are marked *