How to Add Sort by Newest in Magento 2?

Adding a "Sort by Newest" option in Magento 2 enhances customer experience by allowing them to view the latest products first. Below is a step-by-step guide to Magento 2 sort by newest and Magento 2 sort products by newest:

Step 1: Create a Custom Module

1. Directory Structure:

Create a new directory structure for your module:

app/code/Vendor/SortByNewest

2. Module.xml:

Create the module.xml file in app/code/Vendor/SortByNewest/etc/:

<?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_SortByNewest" setup_version="1.0.0"/>

</config>

3. registration.php:

Create the registration.php file in app/code/Vendor/SortByNewest/:

<?php

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

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

    'Vendor_SortByNewest',

    __DIR__

);

 

Step 2: Modify Product Collection

1. Plugin/SortByNewest.php:

Create SortByNewest.php in app/code/Vendor/SortByNewest/Plugin/:

<?php

namespace Vendor\SortByNewest\Plugin;

class SortByNewest {

    public function afterGetAvailableOrders(\Magento\Catalog\Model\Config $subject, $result) {

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

        return $result;

    }

    public function afterGetDefaultSortBy(\Magento\Catalog\Model\Config $subject, $result) {

        return 'created_at';

    }

}

2. Modify di.xml:

Create or modify di.xml in app/code/Vendor/SortByNewest/etc/:

<?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_sort_by_newest" type="Vendor\SortByNewest\Plugin\SortByNewest" />

    </type>

</config>

Step 3: Deploy and Test

1. Enable the Module:

Run the following commands:

php bin/magento module:enable Vendor_SortByNewest

php bin/magento setup:upgrade

php bin/magento cache:flush

2. Test It:

Navigate to your Magento 2 store's product listing page to see the new "Sort by Newest" option, enhancing how you can Magento 2 sort products by newest.

 

For advanced sorting features, check out our Improved Sorting for Magento 2 extension.

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

Loading