• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Magento TagsMagento 2

Product Sort By Price: Low to High and High to Low Magento 2.3

Aug 8, 2020 Editorial Staff 3 Comments

Share
Tweet
Share
5 Shares

Today’s tutorial we are showing, how to add a new filter option in the product listing area of Magento 2.3. Here we are adding price sorting options such as Low to High and  High to Low.

We are not discussing how to create a Magento 2 module here, as we assume you have already a module ready.

Basically we use two different techniques here 1) preference method and 2) plugin method to do necessary overriding of the functionality.

Step #1

Create your di.xml in app/code/[Vendor]/[Module]/etc/frontend/di.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    
    <preference for="Magento\Catalog\Block\Product\ProductList\Toolbar" type="[Vendor]\[Module]\Plugin\Catalog\Block\Toolbar" />

    <type name="Magento\Catalog\Model\Config">
        <plugin name="estore_custom_catalog_model_config" type="[Vendor]\[Module]\Plugin\Catalog\Model\Config"/>
    </type>

    </config>

We are overriding two methods from two files, those responsible for this functionality.

  • afterToOptionArray() from Magento\Catalog\Model\Config
  • setCollection() from Magento\Catalog\Block\Product\ProductList\Toolbar

Step #2

Create  a file called Config.php in the folder  app/code/[Vendor]\[Module]\Plugin\Catalog\Model\Config and add the below code.

<?php

namespace [Vendor]\[Module]\Plugin\Catalog\Model;

class Config
{
    public function afterGetAttributeUsedForSortByArray(
        \Magento\Catalog\Model\Config $catalogConfig,
        $options
    ) {

        unset($options['price']);
        $options['low_to_high'] = 'Price - Low To High';
        $options['high_to_low'] = 'Price - High To Low';
        return $options;

    }

}


In this step we have wrote an after plugin to inject the desired options to toolbar sort. We have unset the already existing price as our new options using for the same purpose.

Step #3

Create a file called Toolbar.php in app/code/[Vendor]/[Module]/Plugin/Catalog/Block and add the below content to it.

<?php
namespace [Vendor]\[Mdouel]\Plugin\Catalog\Block;

class Toolbar extends \Magento\Catalog\Block\Product\ProductList\Toolbar
{

    /**
     * Set collection to pager
     *
     * @param \Magento\Framework\Data\Collection $collection
     * @return \Magento\Catalog\Block\Product\ProductList\Toolbar
     */
    public function setCollection($collection)
    {
        $this->_collection = $collection;

        $this->_collection->setCurPage($this->getCurrentPage());

        // we need to set pagination only if passed value integer and more that 0
        $limit = (int)$this->getLimit();
        if ($limit) {
            $this->_collection->setPageSize($limit);
        }
        if ($this->getCurrentOrder()) {
            if (($this->getCurrentOrder()) == 'position') {
                $this->_collection->addAttributeToSort(
                    $this->getCurrentOrder(),
                    $this->getCurrentDirection()
                );
            } else {
                if ($this->getCurrentOrder() == 'high_to_low') {
                    $this->_collection->setOrder('price', 'desc');
                } elseif ($this->getCurrentOrder() == 'low_to_high') {
                    $this->_collection->setOrder('price', 'asc');
                }

            }
        }
        return $this;
    }

}

This is a preference method that use to override a function in Magento 2.

Step #4

Run the following commands

php bin/magento setup:di:compile
php bin/magento cache:flush

Hope this solved your problem.

Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
  • Just want to thank us? Buy us a Coffee
  • May be another day? Shop on Amazon using our links.
    Your prices won't change but we get a small commission.

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Comments

  1. Dave says

    Jun 16, 2021 at 8:35 pm

    Thank you! After trying numerous options to do this, yours was the only one that worked properly in 2.4.1.

    I changed the if () statement in Toolbar.php to a switch() and added two alphabetical options (which was so easy after reading your code).

    Reply
  2. Gopal Patel says

    May 2, 2022 at 2:30 pm

    Hello Team

    Thanks for your code, its working fine. One more thing i want to add here, if you can add code for like we want to add both option into admin – catalog – storefront – Product Listing Sort by so admin can select it as default sorting option.

    Reply
  3. Atish says

    Apr 24, 2023 at 5:51 am

    It’s working fine on magento2.3 but not working on magento 2.4.
    But thanks for the code

    Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required

Search Here

Share

   

Hot topics

  • How Do I Cancel a Skype Subscription? 8 views
  • Append an element with fade in effect in jQuery 3 views
  • How to get current page URL in PHP? 3 views
  • Replace “\n” with new line characters, using Notepad++ 2 views
  • How to Add Foreign Key in Laravel Migration? 2 views
  • Ubuntu: Add a User To Group www-data 2 views
  • collect.js – A Laravel collection clone in JavaScript 2 views
  • Server Side Form Validation using Regular Expressions 2 views
  • PHP Fatal error: Call to undefined function mssql_connect() while connecting in PHP 2 views
  • What does Model::unguard() do in Laravel? 2 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube

Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com