Skip to content

Elastic Search: Custom sorting options not working after enable elastic search

I’m trying to add custom sorting options like newest products,price high-to-low & price low-to-high in category page using plugin. After creating plugin it’s working good in category page and search page but when i enable amasty’s elastic search module then price high-to-low & price low-to-high sorting working proper in plp but not working in search page.

If from backend settings i’m select “MySql” option then custom sorting working proper and if i’m select elastic search from dropdown then it’s not working.

enter image description here

Also newest product sorting not working in both plp and search page. I have already tried some of solutions suggested in stack as below links but no luck:-

Custom sort by is not working with elastic search in magento 2.3

Magento 2 How to add custom sort by option

Have somebody also faced same issue before? Any suggestions should be appreciated. Thanks.

Following are my module file:-

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="custom_custom_block_toolbar" type="NamespaceModulenamePluginCatalogBlockToolbar" />
    </type>

    <type name="MagentoCatalogModelConfig">
        <plugin name="custom_catalog_model_config" type="NamespaceModulenamePluginCatalogModelConfig" />
    </type>

</config>

Config.php

<?php

namespace NamespaceModulenamePluginCatalogModel;

class Config
{
    public function afterGetAttributeUsedForSortByArray(
    MagentoCatalogModelConfig $catalogConfig,
    $options,
    $requestInfo = null
    ) {
        unset($options['position']);
        $options['high_to_low'] = __('Price - High To Low');
        $options['low_to_high'] = __('Price - Low To High');
        $options['newest'] = __('Newest');
        return $options;

    }

}

Toolbar.php

<?php
namespace NamespaceModulenamePluginCatalogBlock;

class Toolbar
{

    public function aroundSetCollection(
    MagentoCatalogBlockProductProductListToolbar $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');
        }
        elseif ($currentOrder == 'newest') {
            //$subject->getCollection()->setOrder('entity_id', 'desc');
            $subject->getCollection()->setOrder('created_at', 'desc');
        }
    }

    return $result;
    }

}