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.
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="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="custom_custom_block_toolbar" type="Namespace\Modulename\Plugin\Catalog\Block\Toolbar" />
</type>
<type name="Magento\Catalog\Model\Config">
<plugin name="custom_catalog_model_config" type="Namespace\Modulename\Plugin\Catalog\Model\Config" />
</type>
</config>
Config.php
<?php
namespace Namespace\Modulename\Plugin\Catalog\Model;
class Config
{
public function afterGetAttributeUsedForSortByArray(
\Magento\Catalog\Model\Config $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 Namespace\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');
}
elseif ($currentOrder == 'newest') {
//$subject->getCollection()->setOrder('entity_id', 'desc');
$subject->getCollection()->setOrder('created_at', 'desc');
}
}
return $result;
}
}