Skip to content

Magento 2 – Custom sort order not working properly

I have created a custom plugin for sorting options for high to low & low to high price. High to low sort works fine but “low to high” sort order not showing correct results.

app/code/Digital/CustomSort/etc/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="MagentoCatalogBlockProductProductListToolbar">
    <plugin name="digital_customsort_block_product_productlist_toolbar" type="DigitalCustomSortPluginCatalogBlockProductProductListToolbar" />
    </type>
    <type name="MagentoCatalogModelConfig">
        <plugin name="digital_customsort_model_config" type="DigitalCustomSortPluginCatalogModelConfig" />
    </type>
</config>

app/code/Digital/CustomSort/Plugin/Catalog/Model/Config.php

<?php
//namespace DigitalCustomSortPluginModel;
//class Config extends MagentoCatalogModelConfig

namespace DigitalCustomSortPluginCatalogModel;
use MagentoCatalogModelConfig as CatalogConfig;

class Config
{
    public function afterGetAttributeUsedForSortByArray(CatalogConfig $subject, $result)
    {
        $result['low_to_high'] = __('Price - Low To High');
        $result['high_to_low'] = __('Price - High To Low');
        return $result;
    }
}

Digital/CustomSort/Plugin/Catalog/Block/Product/ProductList/Toolbar.php

<?php
 //namespace DigitalCustomSortPluginBlockProductProductList;
 //class Toolbar extends MagentoCatalogBlockProductProductListToolbar

namespace DigitalCustomSortPluginCatalogBlockProductProductList;

use MagentoCatalogBlockProductProductListToolbar as ProductListToolbar;

class Toolbar
{
    public function afterSetCollection(ProductListToolbar $subject, $result, $collection)
    {
        switch ($subject->getCurrentOrder()) {
            case 'low_to_high':
                return $result->getCollection()->setOrder('price', 'asc');
            case 'high_to_low':
                return $result->getCollection()->setOrder('price', 'desc');
            default:
                return $result;
        }
    }
}