How to Add Sort by Option in Magento 2?

Adding a "Sort By" option in Magento 2 can improve the user experience by allowing customers to organize products based on their preferences. Here's a step-by-step guide to Magento 2 add sort by option:

Step 1: Create a Module

  1. Directory Structure:

Create a new directory structure for your module:

app/code/Vendor/CustomSort
  1. module.xml:

Create the module.xml file in app/code/Vendor/CustomSort/etc/ and add the following content:

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

</config>
  1. registration.php:

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

<?php

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

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

    'Vendor_CustomSort',

    __DIR__

);

Step 2: Customize Product Collection

  1. DefaultSorting.php:

Create DefaultSorting.php in app/code/Vendor/CustomSort/Plugin/ to add your logic:

<?php

namespace Vendor\CustomSort\Plugin;

class DefaultSorting {

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

        $result['custom_sort'] = __('Custom Sort');

        return $result;

    }

}
  1. Modify di.xml:

Create or modify di.xml in app/code/Vendor/CustomSort/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_custom_sort" type="Vendor\CustomSort\Plugin\DefaultSorting" />

    </type>

</config>

Step 3: Deploy and Test

  1. Enable the Module:

Run the following command in the terminal:

php bin/magento module:enable Vendor_CustomSort

php bin/magento setup:upgrade

php bin/magento cache:flush
  1. Test It:

Go to your Magento 2 store's product listing page to see the new "Custom Sort" option in the dropdown, enhancing your Magento 2 sort by options.

To unlock even more sorting options and improve your store further, consider trying 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