1

How get Sort By value Relevance in this page.

Using $productListToolbar return only price, name, position value, but I need relevance.

Attached the Screenshot here. mag

1

try to use the below plugin File: Custom\Relevance\etc\frontend\di.xml

<type name="Magento\CatalogSearch\Block\Result">
        <plugin name="Custom_Relevance::getRelvance" type="Custom\Relevance\Plugin\Search\Block\Result" sortOrder="101"/>
</type>

File: Custom\Relevance\Plugin\Search\Block.php

<?php
namespace Custom\Relevance\Plugin\Search\Block;

use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\View\Element\Template\Context as Context;
use Magento\Catalog\Model\Layer\Resolver as LayerResolver;
use Magento\Framework\View\Element\Template as ViewTemplate;
use Magento\Search\Model\QueryFactory;

class Result extends ViewTemplate
{
    public function __construct(
        Context $context,
        LayerResolver $layerResolver,
        QueryFactory $queryFactory,
        array $data =[]
    )
    {
        $this->_catalogLayer = $layerResolver->get();
        $this->_queryFactory = $queryFactory;

        parent::__construct($context, $data);
    }

    public function afterSetListOrders() {

        /* @var $query \Magento\Search\Model\Query */
        //$query = $this->_queryFactory->get();
        //$queryText = $query->getQueryText();


        $category = $this->catalogLayer->getCurrentCategory();
        /* @var $category \Magento\Catalog\Model\Category */
        $availableOrders = $category->getAvailableSortByOptions();
        unset($availableOrders['position']);
        $availableOrders['relevance'] = __('Relevance');


    $directionToSet = 'desc';
        $defaultSortBy = 'relevance';        

        $this->getLayout()->getBlock('search_result_list')->setAvailableOrders(
            $availableOrders
        )->setDefaultDirection(
            $directionToSet
        )->setDefaultSortBy(
            $defaultSortBy
        );
        return $this;

    }
}

Second approach if above not works, using Toolbar

you can implement plugin on the class

\Magento\Catalog\Block\Product\ProductList\Toolbar and method

public function afterGetCurrentOrder() {
    $orders = $this->getAvailableOrders();
        echo '<pre>'; print_r($orders); echo '</pre>';
}

this will give all the sort orders something like below.

Array (
    [name] => Product Name
    [price] => Price
    [manufacturer] => Manufacturer
    [relevance] => Magento\Framework\Phrase Object
        (
            [text:Magento\Framework\Phrase:private] => Relevance
            [arguments:Magento\Framework\Phrase:private] => Array
                (
                )

        )

)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.