How to Add Sort by Date in Magento 2?

Enhance your Magento 2 store by introducing a "Sort by Date" feature, enabling your customers to find the newest items with ease. Follow this quick guide to add this functionality to your store.

Step 1: Create a Custom Module

  1. Directory Setup: Create app/code/Vendor/Module using your chosen vendor/module names.

  2. module.xml: In app/code/Vendor/Module/etc/module.xml, add:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">

    <module name="Vendor_Module" setup_version="1.0.0"/>

</config>
  1. registration.php: In app/code/Vendor/Module/registration.php, add:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Vendor_Module',

    __DIR__

);

 

Step 2: Modify the Product Collection

  1. Create Plugin: Add the following to app/code/Vendor/Module/etc/di.xml:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\Catalog\Model\Config">

        <plugin name="vendor_module_sort" type="Vendor\Module\Plugin\Config" />

    </type>

</config>
  1. Plugin Class: In app/code/Vendor/Module/Plugin/Config.php, include:

<?php

namespace Vendor\Module\Plugin;

class Config

{

    public function afterGetAttributeUsedForSortByArray($subject, $result)

    {

        $result['created_at'] = __('Date');

        return $result;

    }

}

 

Step 3: Activate and Test

  1. Enable Module: Run these commands:

php bin/magento module:enable Vendor_Module

php bin/magento setup:upgrade

php bin/magento cache:clean

php bin/magento cache:flush

 

  1. Verify: Check your store's frontend to confirm the "Sort by Date" option works.

 

If you're looking for more comprehensive sorting options and advanced features, consider exploring  our Improved Sorting for Magento 2 extension. This solution offers enhanced flexibility and a robust set of features to further improve customer satisfaction and drive sales. So that you can create a more intuitive shopping experience tailored to your customers' needs.

Didn’t you find the answer to your question? We are always happy to help you out.

Loading