3

How can I change the default order by value and direction for search results listing page?

The default is set to Relevance but I want to change this permanently to something else i.e. Price for example.

5 Answers 5

9
+50

Try a below code. Tested in M2.3.

This will change the sorting option from Relevance to Price only for Search Result Page.

You can change the $defaultSortBy and $directionToSet as per your need.

File - Custom/SortBy/etc/frontend/di.xml

<type name="Magento\CatalogSearch\Block\Result">
    <plugin name="Custom_SortBy::setPriceSortBy" type="Custom\SortBy\Plugin\Search\Block\Result" sortOrder="100"/>
</type>

File - Custom/SortBy/Plugin/Search/Block/Result.php

<?php
namespace Custom\SortBy\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() {

        $query = $this->_queryFactory->get();
        $queryText = $query->getQueryText();

        $category = $this->_catalogLayer->getCurrentCategory();
        $availableOrders = $category->getAvailableSortByOptions();    
        unset($availableOrders['position']);
        $availableOrders['relevance'] = __('Relevance');

        $directionToSet = 'desc';
        $defaultSortBy = 'price';

        if($queryText == 'ABC') {
          $directionToSet = 'asc';
        } elseif($queryText == 'DEF') {
          $directionToSet = 'desc';
        } else {
          $directionToSet = 'desc';
        }

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

    }
}

File - Custom/SortBy/etc/module.xml if required

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Custom_SortBy">
        <sequence>
            <module name="Magento_CatalogSearch"/>
        </sequence>
    </module>
</config>
4
  • The plugin is a better solution, would it also be possible to change the sort order based on search query, i.e. customer searches for ABC default direction is just changed for that query? Can we pick up the search query in the after method?
    – paj
    Feb 13, 2020 at 8:23
  • @paj yes plugin will maintain the code very well. the term also can be pick up in after method.
    – sandip
    Feb 13, 2020 at 9:36
  • @paj I have updated the answer.
    – sandip
    Feb 13, 2020 at 9:42
  • 1
    This helped a lot thanks.
    – paj
    Feb 13, 2020 at 11:28
2

As mentioned by Martin you can follow those steps but that'll not make any impact on the search result page.

Here's a fix that helped me to achieve the same.

Inside

form.mini.phtml at location /var/www/html/magento2/vendor/magento/module-search/view/frontend/templates

Just add below lines just after the form tag starts.

<input type="hidden" name="product_list_order" value="price" />
<input type="hidden" name="product_list_dir" value="asc" />

Clear the cache and run setup:upgrade and you're good to go.

In case, if you don't want to modify vendor file, you can just create your own module and just extend the same file.

2

For only Search result page you need to override Magento\CatalogSearch\Block\Result file as below:

1.Edit your module's di.xml file, add below preference,

    <preference for="Magento\CatalogSearch\Block\Result" type="Vendor\Module\Block\Search\Result" />

2. Add New block Result as mention above:

namespace Vendor\Module\Block\Search;

class Result extends \Magento\CatalogSearch\Block\Result
{
  public function setListOrders()
  {
      $category = $this->catalogLayer->getCurrentCategory();
      /* @var $category \Magento\Catalog\Model\Category */
      $availableOrders = $category->getAvailableSortByOptions();
      unset($availableOrders['position']);
      $availableOrders['relevance'] = __('Relevance');

      $this->getListBlock()->setAvailableOrders(
          $availableOrders
      )->setDefaultDirection(
          'desc'
      )->setDefaultSortBy(
          'price'
      );
      // 'price' you can set any attribute here ex.: name, price, any custom attribute
      return $this;
  }
}

Let me know if not working.

1

If you mean the order by which the product's are outputted on the product listing page(Category View) then there is a configuration in the backend of Magento 2 to change that. The Config is Under:

"Stores" -> "Configuration" -> "Catalog" -> "Catalog" -> "Storefront" -> "Product Listing Sort by"

Not sure if this applied to the Search Result page though.

1
  • that does not apply to search results.
    – paj
    Jan 23, 2020 at 17:53
0

For this, you need to override the Magento core block file. Step 1: create di.xml file with below code in etc folder.

Step 2: Create Result.php file in Vendor\Module\Block\Search folder. Add below code in it. catalogLayer->getCurrentCategory(); /* @var $category \Magento\Catalog\Model\Category */ $availableOrders = $category->getAvailableSortByOptions(); unset($availableOrders['position']); $availableOrders['relevance'] = __('Relevance'); $this->getListBlock()->setAvailableOrders( $availableOrders )->setDefaultDirection( 'desc' )->setDefaultSortBy( 'price' ); return $this; } } ?>

Or

If you are not familiar with Magento coding then I suggest you use Solwin Advanced Sorting Magento 2 extension.

Advanced Sorting Magento 2 extension will add custom sorting options to your store to make the product search process easier for customers.

Refer the link below: https://www.solwininfotech.com/product/magento-2-extensions/advanced-sorting-magento-2/

2
  • Already said in above post..
    – Rik Patel
    Feb 13, 2020 at 10:35
  • 2
    When linking to your own site or content (or content that you are affiliated with), you must disclose your affiliation in the answer in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy.
    – cigien
    May 8, 2021 at 14:34

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.