ÉricP
ÉricP

Reputation: 853

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:

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'))

Upvotes: 3

Views: 5093

Answers (4)

Allan
Allan

Reputation: 1

Better:

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

Upvotes: 0

Keven Ages
Keven Ages

Reputation: 41

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.

Upvotes: 0

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25968

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.

Upvotes: 0

clockworkgeek
clockworkgeek

Reputation: 37700

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');

Upvotes: 1

Related Questions