I am trying to sort the Product collection based on the attribute option value,
I used below plugin
Vendor/Module/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\Layer">
<plugin name="custom_product_model_layer" type="Vednor\Module\Plugin\Layer" />
</type>
</config>
Then in Vendor/Module/Plugin/Layer.php
namespace Vendor\Module\Plugin;
class Layer
{
private $logger;
public function __construct(
\Psr\Log\LoggerInterface $logger
) {
$this->logger = $logger;
}
public function aroundGetProductCollection(
\Magento\Catalog\Model\Layer $subject,
\Closure $proceed
) {
$result = $proceed();
$result->addAttributeToSort('brand', 'puma');
return $result;
}
}
Second Method:
di.xml
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
<plugin name="custom_product_toolbar" type="Vendor\Module\Plugin\Toolbar" />
</type>
Then Vendor/Module/Plugin/Toolbar.php
namespace Vendor\Module\Plugin;
class Toolbar
{
protected $_objectManager;
protected $request;
private $logger;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager,
\Magento\Framework\App\Request\Http $request,
\Psr\Log\LoggerInterface $logger
) {
$this->_objectManager = $objectmanager;
$this->request = $request;
$this->logger = $logger;
}
public function aroundSetCollection(
\Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
\Closure $proceed,
$request
) {
$result = $proceed($request);
$this->_collection = $request;
$currentOrder = $subject->getCurrentOrder();
$category = $this->_objectManager->get('Magento\Framework\Registry')->registry('current_category');
if ($category) {
$page = $this->request->getParam('p');
if ($page == '') {
$page = 1;
}
$this->_collection->getCurPage();
$this->_collection->setCurPage($page);
}
if ($currentOrder) {
if ($currentOrder == 'relevance') {
// Suggest me the logic here
}
}
return $result;
}
}
I have created a attribute called "brand" so whenever the product is searched, I need to load the products on top which are set as "puma" option for that particular attribute.
I am trying with Both methods, but both are not working, can I get any help on this. Thanks in advance!!