How to Add Magento 2 Sort by Price for Low to High & High to Low Options

How to Add Magento 2 Sort By Price- Low to High and High to Low

Hello Magento Folks,

How are you all? Have you all took the advantage of the MageComp Diwali offers? It’s the last day for MageComp Big Diwali Sale 2020. Shop now and get huge discounts on Magento Extensions and Services. In this article, I will guide you How to Add Magento 2 Sort by Price for Low to High & High to Low Options. Let’s get started. 

Quick Intro:

Ecommerce stores must have precise and user-friendly navigation that makes the customers way easy to shop from your store. Sorting is a major component to provide for user’s ease and effortless searching for the product they are finding. By default, Magento 2 is capable of providing the below-given options such as by position, product name, and price. 

Config_2

Many times the customers are looking for the cheapest products and some of the customers need the high-priced products then for them the above sorting options are not efficient. For offering the options of sort by price for low to high & high to low in Magento 2 follow the below-given steps.

Steps to Add Magento 2 Sort by Price for Low to High & High to Low Options:

Step 1: create registration.php file in app\code\Vendor\Extension

<?php
\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_Extension',
_DIR_
);

Step 2: Create module.xml file in app\code\Vendor\Extension\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_Extension" setup_version="1.0.0"/>
</config>

Step 3: Create di.xml file in app\code\Vendor\Extension\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\Block\Product\ProductList\Toolbar">
<plugin name="custom_custom_block_toolbar" type="Vendor\Extension\Plugin\Catalog\Block\Toolbar"/>
</type>
<type name="Magento\Catalog\Model\Config">
<plugin name="custom_catalog_model_config" type="Vendor\Extension\Plugin\Catalog\Model\Config"/>
</type>
</config>

Step 4: Create Toolbar.php file in app\code\Vendor\Extension\\Plugin\Catalog\Block

<?php
namespace Vendor\Extension\Plugin\Catalog\Block;
class Toolbar
{
public function aroundSetCollection(\Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
\Closure $proceed, $collection)
{
$currentOrder = $subject->getCurrentOrder();
$result = $proceed($collection);
if($currentOrder)
{
if($currentOrder == 'high_to_low')
{
$subject->getCollection()->setOrder('price', 'desc');
}
elseif ($currentOrder == 'low_to_high')
{
$subject->getCollection()->setOrder('price', 'asc');
}
}
else
{
$subject->getCollection()->getSelect()->reset('order');
$subject->getCollection()->setOrder('price', 'asc');
}
return $result;
}
}

Step 5: Create Config.php file in app\code\Vendor\Extension\Plugin\Catalog\Model

<?php
namespace Vendor\Extension\Plugin\Catalog\Model;
class Config
{
public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig,
$results)
{
$results['low_to_high'] = __('Price - Low To High');
$results['high_to_low'] = __('Price - High To Low');
return $results;
}
}

That’s it.

After implementing the above solution:

Config_1

Conclusion:

Most probably all are successfully able to provide sort options of Low to High & High to Low with the help of the above code. In case of any troubles write it down in the comments I will help you.

Also, share the illustration with your E-commerce friends and help them to provide sorting options in their Magento 2 store. 

Happy Reading!

Magento-development-services

Previous Article

How to Add Tracking Number to the Current Order Shipment in Magento 2

Next Article

How to Add Date & Time Picker in Magento 2 System Configuration With Custom Format

Write a Comment
  1. udhai developer

    Hi,
    I am using Magento 2.4.3 and when apply the sorting returns an empty page.

    Please help me on this issue?

      1. You should get an error in your logs due to ElasticSearch not allowing (in the latest versions) sorting by an attribute that doesn’t exist.

        I’m also looking for a solution at the moment.

        1. kevin ruscoe

          I fixed it by hooking into the afterGetSort() interceptor on Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort to pull the product_list_order querystring value and send that to elasticsearch. You’ll need to disable the Toolbar interceptor part of this though

          1. Hi Kevin. What was the code you used to send the values to elasticsearch please? I have created a plugin on Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort add added a afterGetSort() method which looks like the following:

            public function afterGetSort(
            \Magento\Elasticsearch\SearchAdapter\Query\Builder\Sort $subject, $sorts
            ){
            $sorts[] = [
            ‘product_list_order’ => [
            ‘order’ => $this->request->getQuery(‘product_list_order’)
            ]
            ];

            return $sorts;
            }

            But I get this in the error logs:
            “No mapping found for [product_list_order] in order to sort on”,”index_uuid”

            Many thanks

          2. Hello kevin,

            Can you please share your plugin file code, I tried according to your suggestion but still facing issue.

            Thanks!

  2. Vishal Thakur

    Hello, The above code is not working in the latest versions of Magento 2.4.*
    Sorting options are showing fine but getting blank results after selecting any option (Price – Low To High, Price – High To Low).
    Here is the SQL Query of “Toolbar.php” after debug —-

    SELECT `e`.*, `price_index`.`price`, `price_index`.`tax_class_id`, `price_index`.`final_price`, IF(price_index.tier_price IS NOT NULL, LEAST(price_index.min_price, price_index.tier_price), price_index.min_price) AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price`, IFNULL(review_summary.reviews_count, 0) AS `reviews_count`, IFNULL(review_summary.rating_summary, 0) AS `rating_summary`, `stock_status_index`.`stock_status` AS `is_salable` FROM `catalog_product_entity` AS `e` INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.customer_group_id = 0 AND price_index.website_id = ‘1’ LEFT JOIN `review_entity_summary` AS `review_summary` ON e.entity_id = review_summary.entity_pk_value AND review_summary.store_id = 1 AND review_summary.entity_type = (SELECT `review_entity`.`entity_id` FROM `review_entity` WHERE (entity_code = ‘product’)) INNER JOIN `cataloginventory_stock_status` AS `stock_status_index` ON e.entity_id = stock_status_index.product_id WHERE (stock_status_index.stock_status = 1) AND (NULL)

    1. Kindly check your implementation of the code properly and run the caching and indexing command once and then check. If you are still facing issue, do let us know,

  3. Hi,
    I am using Magento 2.4.3 and when apply the sorting returns an empty page.

    Please help me on this issue?
    This is my log file…

    {“error”:{“root_cause”:[{“type”:”query_shard_exception”,”reason”:”No mapping found for [latest] in order to sort on”,”index_uuid”:”I3G2NzxbTqmwVYe389_5FQ”,”index”:”m243p1_product_1_v98″}],”type”:”search_phase_execution_exception”,”reason”:”all shards failed”,”phase”:”query”,”grouped”:true,”failed_shards”:[{“shard”:0,”index”:”m243p1_product_1_v98″,”node”:”gpfIGR9vQGmSfdmg0tZOTQ”,”reason”:{“type”:”query_shard_exception”,”reason”:”No mapping found for [latest] in order to sort on”,”index_uuid”:”I3G2NzxbTqmwVYe389_5FQ”,”index”:”m243p1_product_1_v98″}}]},”status”:400} {“exception”:”[object] (Elasticsearch\\Common\\Exceptions\\BadRequest400Exception(code: 400): {\”error\”:{\”root_cause\”:[{\”type\”:\”query_shard_exception\”,\”reason\”:\”No mapping found for [latest] in order to sort on\”,\”index_uuid\”:\”I3G2NzxbTqmwVYe389_5FQ\”,\”index\”:\”m243p1_product_1_v98\”}],\”type\”:\”search_phase_execution_exception\”,\”reason\”:\”all shards failed\”,\”phase\”:\”query\”,\”grouped\”:true,\”failed_shards\”:[{\”shard\”:0,\”index\”:\”m243p1_product_1_v98\”,\”node\”:\”gpfIGR9vQGmSfdmg0tZOTQ\”,\”reason\”:{\”type\”:\”query_shard_exception\”,\”reason\”:\”No mapping found for [latest] in order to sort on\”,\”index_uuid\”:\”I3G2NzxbTqmwVYe389_5FQ\”,\”index\”:\”m243p1_product_1_v98\”}}]},\”status\”:400} at C:\\xampp\\htdocs\\m243p1\\vendor\\elasticsearch\\elasticsearch\\src\\Elasticsearch\\Connections\\Connection.php:675)”} []
    have you any solution ?

      1. yes, confirm there is not any confilct with other extensions or theme files because i have use Magento-Luma theme .

  4. It’s showing error “We can’t find products matching the selection.” when selecting “Price – Low To High” and also got “No mapping found for [low_to_high] in order to sort on” on exception.log
    It is not working on Magento 2.4.3
    please provide solution for Magento version 2.4.3

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨