enter code here
I am created a custom sorting in magento2.4.3p1 but it is not working in the frontend.
I am face issues is
We can't find products matching the selection.
Toolbar.php
<?php
namespace Bay20\Sorting\Plugin\Product\ProductList;
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 $toolbar,
\Closure $proceed,
$collection
) {
$this->_collection = $collection;
$currentOrder = $toolbar->getCurrentOrder();
$currentDirection = $toolbar->getCurrentDirection();
$result = $proceed($collection);
if ($currentOrder) {
switch ($currentOrder) {
case 'newest':
$this->_collection
->getSelect()
->order('e.created_at DESC');
break;
case 'oldest':
$this->_collection
->getSelect()
->order('e.created_at ASC');
break;
case 'price_desc':
$this->_collection
->getSelect()
->order('price_index.min_price DESC');
break;
case 'price_asc':
$this->_collection
->getSelect()
->order('price_index.min_price ASC');
break;
case 'name_az':
$this->_collection
->addAttributeToSort('name', 'asc');
break;
case 'name_za':
$this->_collection
->addAttributeToSort('name', 'desc');
break;
default:
$this->_collection
->setOrder($currentOrder, $currentDirection);
break;
}
}
return $result;
}
}
Also I have created config.php
<?php
namespace Bay20\Sorting\Plugin\Model;
class Config
{
/**
* Adding custom options and changing labels
*
* @param \Magento\Catalog\Model\Config $catalogConfig
* @param [] $options
* @return []
*/
public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
{
//Remove default sorting options
/*unset($options['position']);
unset($options['name']);*/
unset($options['price']);
//Change label of default sorting options if needed
//$options['position'] = __('Relevance');
//New sorting options
$options['price_desc'] = __('Price High - Low');
$options['price_asc'] = __('Price Low - High');
$options['newest'] = __('Newest');
$options['oldest'] = __('Oldest');
$options['name_az'] = __('Product Name A - Z');
$options['name_za'] = __('Product Name Z - A');
return $options;
}
}
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\Model\Config">
<plugin name="Bay20_Sorting::addCustomSortOptions" type="Bay20\Sorting\Plugin\Model\Config" />
</type>
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="Bay20_Sorting::implementCustomSortOptions" type="Bay20\Sorting\Plugin\Product\ProductList\Toolbar" />
</type>
</config>