Magento 2 - Add custom sort by option in cattegory page and make it default
-
21-02-2021 - |
Question
I have added custom sort by option "random" for category page. I have used following code to add random option:
I have used plugin .
app/code/DL/CustomSortOption/etc/frontend/di.xml
<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="sortby_add_custom_option" type="DL\CustomSortOption\Plugin\Model\Config" />
</type>
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="sortby_extend_default_sort_filters" type="DL\CustomSortOption\Plugin\Block\Toolbar" />
</type>
app/code/DL/CustomSortOption/Plugin/Model/Config:
<?php
namespace DL\CustomSortOption\Plugin\Model;
class Config
{
public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
{
$customOption['random'] = __('Random');
$options = array_merge($customOption, $options);
return $options;
}
}
?>
app/code/DL/CustomSortOption/Plugin/Block/Toolbar
<?php
namespace DL\CustomSortOption\Plugin\Block;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Select;
class Toolbar
{
protected $_collection;
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 'random':
$this->_collection
->getSelect()
->order('RAND()');
break;
default:
$this->_collection
->setOrder($currentOrder, $currentDirection);
break;
}
}
//var_dump((string) $this->_collection->getSelect()); You can use this to get a list of all the available sort fields
return $result;
}
}
?>
This new option Random which I added is working fine and appears in sort by drop-down in front-end on category page. I want this new option to be made default so when user opens category page it should be applied by default.
}
Solution
I think you can create a plugin method before the setDefaultOrder($field)
method in the toolbar Block. For example the following short method should do it (add it into app/code/DL/CustomSortOption/Plugin/Block/Toolbar
and configure it in di.xml
):
public function beforeSetDefaultOrder(
\Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar,
$field)
{
//if the 'random' is not set as sort order at this moment,
//you need to add it like below with addOrderToAvailableOrders
//$toolbar->addOrderToAvailableOrders('random', 'random');
//set the input parameter to 'random'
return ['random'];
}