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

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

Create di.xml

Directory

app\code\VendorName\ModuleName\etc\di.xml

Content of di.xml

<?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="VendorName\ModuleName\Plugin\Catalog\Block\Toolbar"/>
</type>
<type name="Magento\Catalog\Model\Config">
<plugin name="custom_catalog_model_config" type="VendorName\ModuleName\Plugin\Catalog\Model\Config"/>
</type>
</config>

Create Toolbar.php

Directory

app\code\VendorName\ModuleName\Plugin\Catalog\Block\Toolbar.php

Content of Toolbar.php

<?php
namespace VendorName\ModuleName\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;
}
}

Create Config.php

Directory

app\code\VendorName\ModuleName\Plugin\Catalog\Model\Config.php

Content of Config.php

<?php
namespace VendorName\ModuleName\Plugin\Catalog\Model;
class Config
{
public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
{
$options['low_to_high'] = __('Price - Low To High');
$options['high_to_low'] = __('Price - High To Low');
return $options;
}
}
If you are looking for Magento Developers, visit Magento Developer Agency.
Related Products