开发者

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('crea开发者_StackOverflow社区ted_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'))


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


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.


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.


Better:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜