How to fix Magento 2.4.x sort by position category products issue

By | March 10, 2022
Spread the love

This is very common problem which is being faced by all of magento 2 stores. Even Magento support saying it is fixed but still it is not working old stores which have customized plugins.

So simple fix it, go to file location vendor/magento/module-catalog-search/Model/ResourceModel/Fulltext/Collection.php

We have to update function _renderFiltersBefore.

See below function

/**
     * @inheritdoc
     */
    protected function _renderFiltersBefore()
    {
        
        /**
           * @var \Magento\Framework\App\RequestInterface $request
        */
        if(isset($_SERVER['REQUEST_URI']) && !stristr($_SERVER['REQUEST_URI'], "catalogsearch")){
             $request = ObjectManager::getInstance()->create("\Magento\Framework\App\RequestInterface");
             if($request->getParam("product_list_order")){
                  $attribute = $request->getParam("product_list_order", "position");
                  $direction = $request->getParam("product_list_dir", "asc");

                  $this->addAttributeToSort($attribute, $direction);
             }
             else{
                $this->addAttributeToSort("position", "asc");
             }
        }

        if ($this->isLoaded()) {
            return;
        }

        if ($this->searchRequestName !== 'quick_search_container'
            || strlen(trim($this->queryText))
        ) {
            $this->prepareSearchTermFilter();
            $this->preparePriceAggregation();
            
            $searchCriteria = $this->getSearchCriteriaResolver()->resolve();
            try {
                $this->searchResult =  $this->getSearch()->search($searchCriteria);
                $this->_totalRecords = $this->getTotalRecordsResolver($this->searchResult)->resolve();
            } catch (EmptyRequestDataException $e) {
                $this->searchResult = $this->createEmptyResult();
            } catch (NonExistingRequestNameException $e) {
                $this->_logger->error($e->getMessage());
                throw new LocalizedException(__('An error occurred. For details, see the error log.'));
            }
        } else {
            $this->searchResult = $this->createEmptyResult();
        }

        $this->getSearchResultApplier($this->searchResult)->apply();
        parent::_renderFiltersBefore();
    }

To override file add following code to di.xml

<virtualType name="Magento\CatalogSearch\Model\ResourceModel\Fulltext\CollectionFactory" type="Magento\Catalog\Model\ResourceModel\Product\CollectionFactory">
    <arguments>
        <argument name="instanceName" xsi:type="string">Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext\Collection</argument>
    </arguments>
</virtualType>

<virtualType name="elasticsearchCategoryCollection" type="Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext\Collection"/>
<virtualType name="elasticsearchFulltextSearchCollection" type="Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext\Collection"/>

<preference for="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection" type="Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext\Collection"/>

 

Create file with following code Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext\Collection.php

<?php

namespace Techgroup\Addon\Model\CatalogSearch\ResourceModel\Fulltext;

use Magento\Framework\App\ObjectManager;

class Collection extends \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection
{
    protected function _renderFiltersBefore()
    {
        /**
          * @var \Magento\Framework\App\RequestInterface $request
        */
        if(isset($_SERVER['REQUEST_URI']) && !stristr($_SERVER['REQUEST_URI'], "catalogsearch")){
            $request = ObjectManager::getInstance()->create("\Magento\Framework\App\RequestInterface");
            if($request->getParam("product_list_order")){
                $attribute = $request->getParam("product_list_order", "position");
                $direction = $request->getParam("product_list_dir", "asc");

                $this->addAttributeToSort($attribute, $direction);
            }
            else{
               $this->addAttributeToSort("position", "asc");
            }
        }
        
        parent::_renderFiltersBefore();
    }
}