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

By | November 22, 2021
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.

if(!$this->searchOrders){
     $this->setSearchOrder(“position”, ‘asc’);
}

/**
     * @inheritdoc
     */
    protected function _renderFiltersBefore()
    {
        if ($this->isLoaded()) {
            return;
        }

        if ($this->searchRequestName !== 'quick_search_container'
            || strlen(trim($this->queryText))
        ) {
            $this->prepareSearchTermFilter();
            $this->preparePriceAggregation();
            
            if(!$this->searchOrders){
                $this->setSearchOrder("position", 'asc');
            }

            $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();
    }