Menu Close
    Hire Us Request Quote Reading List Switch to Dark Mode

    How To Add More Sorting Fields in Magento 2

    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.

    <?php
    namespace Vendor\ModuleName\Plugin;
    
    class Config
    {
        public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
        {
            $options[] = ["latest" => __("Latest Product")]
            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);
        }
    }

    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.

     

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close