Back to Top

How To Add More Sorting Fields in Magento 2

Updated 27 February 2024

How To Add More Sorting Fields in Magento 2:- In this blog I’m going to explain how we can add more sorting fields on product collection page or category page.

In order to add more sorting fields you need to follow below steps.

Step 1: Make plugin of Class Magento\Catalog\Model\Config and Magento\Catalog\Block\Product\ProductList\Toolbar  by defining it’s entry in di.xml.

So, lets create a di.xml file in app/code/Vendor/ModuleName/etc directory and write below code..

<?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="catalog_config_plugin" type="Vendor\ModuleName\Plugin\Config" />
    </type>
    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="catalog_productlist_toolbar_plugin" type="Vendor\ModuleName\Plugin\Product\ProductList\Toolbar" />
    </type>
</config>

Step 2: Create Config.php file under app/code/Vendor/ModuleName/Plugin directory and write below code.

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
namespace Vendor\ModuleName\Plugin;

class Config
{
    public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
    {
        $customOption['latest'] = __("Latest Product");
        $options = array_merge($options,$customOption);

        return $options;
    }
}

This will add a new sorting field.

Step 3: Create Toolbar.php file under Vendor\ModuleName\Plugin\Product\ProductList directory and write below code.

<?php
namespace Vendor\ModuleName\Plugin\Product\ProductList;

class Toolbar
{
    public function aroundSetCollection(
        \Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
        \Closure $proceed,
        $collection
    ) {
        $currentOrder = $subject->getCurrentOrder();
        if ($currentOrder == "latest ) {
            $dir = $subject->getCurrentDirection();
            $collection->getSelect()->order('created_at '.$dir); // you can add filter as per your requirement.
        }
        return $proceed($collection);
    }
}
latestproduct

In this way we can add custom sorting fields as per our requirement.. hope it will be helpful for you. 🙂

If you will face any issue then comment below.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • Tanmay
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home