I add two option in sort by drop down for product price (high to low) and (low to hight).
app/code/VendoreName/ModuleName/etc
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">
<!-- for add option in sort by drop down -->
<type name="Magento\Catalog\Model\Config">
<plugin name="addOptions" type="VendoreName\ModuleName\Plugin\Model\Config" />
</type>
<!-- for do process for sort by option vise -->
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="addPriceFilter" type="VendoreName\ModuleName\Plugin\Product\ProductList\Toolbar" />
</type>
</config>
app/code/VendoreName/ModuleName/Plugin/Model
Config.php
<?php
namespace VendoreName\ModuleName\Plugin\Model;
use Magento\Store\Model\StoreManagerInterface;
class Config
{
protected $_storeManager;
public function __construct(
StoreManagerInterface $storeManager
) {
$this->_storeManager = $storeManager;
}
public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
{
$store = $this->_storeManager->getStore();
$currencySymbol = $store->getCurrentCurrency()->getCurrencySymbol();
//Remove specific default sorting options
//unset($options['position']);
//unset($options['name']);
unset($options['price']); // here i remove price option
//Changing label
//$customOption['position'] = __('Relevance');
//New sorting options
$customOption['price_desc'] = __($currencySymbol.' (High -> Low)');
$customOption['price_asc'] = __($currencySymbol.' (Low -> High)');
//Merge default sorting options with custom options
$options = array_merge($customOption, $options);
return $options;
}
}
app/code/VendoreName/ModuleName/Plugin/Product/ProductList
Toolbar.php
<?php
namespace VendoreName\ModuleName\Plugin\Product\ProductList;
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 == 'price_desc') {
$subject->getCollection()->setOrder('price', 'desc');
} elseif ($currentOrder == 'price_asc') {
$subject->getCollection()->setOrder('price', 'asc');
}
}
return $result;
}
}
here we can apply our custom filter also like custom attribute value or some other product value. by using addFieldToFilter().
I Hope This Helps You.