Magento Tutorials

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

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. 

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:

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!

Click to rate this post!
[Total: 9 Average: 4.9]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • 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

  • 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 ?

  • 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)

    • 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,

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

    Please help me on this issue?

      • 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.

        • 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

          • Hello kevin,

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

            Thanks!

          • 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

Recent Posts

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

2 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

2 days ago

Magento 2: How to Add Header and Footer in Checkout

Hello Magento Friends, In today’s blog, we will discuss adding a header and footer to…

3 days ago

Understanding Flexbox Layout in React Native

Hello React Native Friends, Building a visually appealing and responsive mobile app is crucial in…

5 days ago

HYVĂ„ Themes Releases: 1.3.6 & 1.3.7 – What’s New

We're thrilled to announce the release of Hyvä Themes 1.3.6 and 1.3.7! These latest updates…

5 days ago

How Modern E-Commerce Platforms Leverage Docker & Kubernetes for Scalability

Your e-commerce platform is surging - orders are rolling in, traffic spikes are becoming the…

6 days ago