19

How can I make Magento sort products in the catalog by the date they were added? This isn't an option in the admin so guessing it needs to be done in the code somewhere.

Thanks.

a1anm
  • 1,617
  • 11
  • 45
  • 78

8 Answers8

44

It is quite easy to add a sorting by date option if you're OK (you shouldn't be) with modifying core files. Simply modify app/code/core/Mage/Catalog/Model/Config.php file as in example below:

public function getAttributeUsedForSortByArray()
{
    $options = array(
        'position'  => Mage::helper('catalog')->__('Position'),

        // HERE IS OUR NEW OPTION
        'created_at' => Mage::helper('catalog')->__('Date')
    );
    foreach ($this->getAttributesUsedForSortBy() as $attribute) {
        /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
        $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
    }

    return $options;
}

It is not so easy, if you are not into modifying core files. In that case you must create this bunch of files:

app/etc/modules/Stackoverflow_Catalog.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Stackoverflow_Catalog>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Catalog />
            </depends>
        </Stackoverflow_Catalog>
    </modules>
</config>

app/code/local/Stackoverflow/Catalog/etc/config.xml

<?xml version="1.0"?>
<config>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <config>Stackoverflow_Catalog_Model_Config</config>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

app/code/local/Stackoverflow/Catalog/Model/Config.php

<?php

class Stackoverflow_Catalog_Model_Config extends Mage_Catalog_Model_Config {
    public function getAttributeUsedForSortByArray() {
        $options = parent::getAttributeUsedForSortByArray();
        if (!isset($options['created_at'])) {
            $options['created_at'] = Mage::helper('catalog')->__('Date');
        }
        return $options;
    }
}

TIP: Go for a clean way, it will pay of in a long run.

Vilius Paulauskas
  • 3,121
  • 3
  • 24
  • 24
  • 4
    don't care if it's an old answer, it saved me an hour or two +1 tx! – giorgio Feb 27 '12 at 13:31
  • It is not recommended, and is poor form to suggest modifying Magento core files. You've now just set them up to "break" the site the very next time an update is installed, OR to prevent them from ever being able to update their Magento core. – random_user_name Mar 17 '12 at 17:06
  • 3
    I am not suggesting anything, I've provided both methods showing how to solve the issue. It is up to you which one you choose. – Vilius Paulauskas Apr 02 '12 at 08:50
  • 3
    Actually, app/code/core/Mage/Catalog/Model/Config.php can also be copied to app/code/local/Mage/Catalog/Model/Config.php and just add the 'Date' option there. This way, NO core files are touched. Thanks Vilius for the solution. – datasn.io Sep 19 '12 at 09:42
  • 1
    How to do that to see it on admin side? This only works for Frontend. – Sonhja Dec 26 '12 at 11:23
  • 3
    How can I make this the DEFAULT method for sorting the products? – datasn.io Jul 03 '13 at 05:08
  • 1
    Works great, but you forgot to close the config element in the `app/code/local/Stackoverflow/Catalog/etc/config.xml` file – Daniel West Jun 10 '15 at 12:35
  • 1
    in my installation its displayed but when i choose it it returns 404 in url:/sort-by/created_at/desc – aimiliano Oct 24 '16 at 11:06
14

Place this code into your local.xml no need to override any Magento core files.

If you override any Magento core files in future upgrade problem will occur

<layout>
<catalog_category_default>
    <reference name="product_list">
        <action method="setAvailableOrders" json="value">
            <value><![CDATA[
                           {"created_at" : "Latest","price":"Price"}
                   ]]>
            </value>
        </action>
    </reference>
    <reference name="product_list_toolbar">
        <action method="setDefaultDirection">
            <dir>desc</dir>
        </action>
    </reference>
</catalog_category_default>
</layout>
user1553711
  • 141
  • 1
  • 3
13

I solved this by copying app/code/core/Mage/Catalog/Block/Product/List.php into app/code/local and adding some sorting code at the end of its _getProductCollection() method:

// sort by created_at date or entity_id
if(!isset($_GET['order'])) {
    $this->_productCollection->getSelect()->reset( Zend_Db_Select::ORDER );
    $this->_productCollection->getSelect()->order('e.entity_id desc');
}
return $this->_productCollection;

You can use either 'e.entity_id desc' or 'e.created_at desc' to sort.

enru
  • 131
  • 1
  • 4
  • +1 for a solution that does not touch core files, but rather creates an extension of sorts. – random_user_name Mar 17 '12 at 17:07
  • 1
    @cale_b: The solution copies a core file in to local and then makes changes there which as you would say, is "poor form", because that is the wrong way to rewrite the core. The second method Vilius Pau suggests is the correct way to rewrite the core, and is a far better solution. – jmspldnl Jul 10 '12 at 18:24
  • Save me lot of time. I wanted to reset all the sorting option if order=entity_id and above code is great for that – dashbh Jan 23 '14 at 14:34
11

Like this

$_newest_productCollection = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setOrder('created_at', 'desc')
$_newest_productCollection->load();
Marlon Creative
  • 3,756
  • 19
  • 55
  • 76
  • -1 for missing the point of the question. The answer returns a product collection sorted by `created_at`, whereas the question was how to sort products in the catalog (presumably on the category page) by `created_at`. – Toby Hemmerling Aug 17 '11 at 13:48
  • Perhaps this did miss the point of the question, however this was the answer i was looking for! Many thanks. – Jimmery Aug 03 '15 at 13:19
2

Yust for update (works with Mage 1.7.0.2): in an setupscript of an own module:

$installer = $this;
$installer->startSetup();

$productEntityTypeId = Mage::getModel('catalog/product')->getResource()->getEntityType()->getId();

//lets change created_at properties
//////////////////////////////////////////////////
$installer->updateAttribute($productEntityTypeId, 'created_at', array(
    'visible_on_front' => true,
    'used_in_product_listing' => true
    'used_for_sort_by' => 1,
    'frontend_label' => 'Created at'
));

$installer->endSetup();

// mark index as "reindex required"
$indexerCodes = array(
    'catalog_product_flat'
);
$indexer = Mage::getModel('index/process');
foreach ($indexerCodes as $code) {
    $indexer->load($code, 'indexer_code')
        ->changeStatus(Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX);
}

and in the catalog.xml layout handle:

<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
...
<action method="setDefaultDirection"><dir>desc</dir></action>
</block>

After this you can select created_at as default sorting in the system configuration or in the catagory display settings

Marcel Lange
  • 1,504
  • 1
  • 13
  • 15
1

I'm not sure that there is an easy way to do that, without digging into the core code. However, I haven't tried this but it seems like it should work:

Create a new Date attribute. You'll see that there is an option at the bottom of the attribute options called "Used for sorting in product listing". Select Yes for that. Then and add it to your attribute group. Then when you add a product, just select the current date, and you should be able to use that for sorting. To set the default of that, go into System >> Configuration >> Catalog >> Frontend and you'll see your attribute in the "Product listing sort by" option.

Hope that works out for you.

Prattski
  • 2,055
  • 2
  • 13
  • 16
0

I've done it by rewriting the class:

Mage_Catalog_Model_Category_Attribute_Source_Sortby

and function:

public function getAllOptions()
{
    if (is_null($this->_options)) {
        $this->_options = array(array(
            'label' => Mage::helper('catalog')->__('Best Value'),
            'value' => 'position'
        ));
        $this->_options = array(array(
            'label' => Mage::helper('catalog')->__('Created At'),
            'value' => 'created_at'
        ));
        foreach ($this->_getCatalogConfig()->getAttributesUsedForSortBy() as $attribute) {
            $this->_options[] = array(
                'label' => Mage::helper('catalog')->__($attribute['frontend_label']),
                'value' => $attribute['attribute_code']
            );
        }
    }
    return $this->_options;
}
ahe_borriglione
  • 467
  • 4
  • 11
0

You can try below

app/code/core/mage/catalog/model/resource/eav/mysql4/product/collection.php

in "public function addAttributeToSort($attribute, $dir='asc')"

after

$this->getSelect()->order("cat_index_position {$dir}");

add this

$this->getSelect()->order("e.entity_id desc");
Techie
  • 44,706
  • 42
  • 157
  • 243