Question

Can you suggest me how to change the sorting option on my site? I am using Magento 2.3.1.

Was it helpful?

Solution

You need to create custom extension for it:

app/code/Vendorname/Modulename/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="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>

Now Create Config.php file

app/code/Vendorname/Modulename/Plugin/Catalog/Model/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;

    }

}

Now Create Toolbar.php file

app/code/Vendorname/Modulename/Plugin/Catalog/Block/Toolbar.php

<?php
namespace Vendorname\Modulename\Plugin\Catalog\Block;

class Toolbar
{

    /**
    * Plugin
    *
    * @param \Magento\Catalog\Block\Product\ProductList\Toolbar $subject
    * @param \Closure $proceed
    * @param \Magento\Framework\Data\Collection $collection
    * @return \Magento\Catalog\Block\Product\ProductList\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');
        }
    }

    return $result;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top