Changing Magento Search Sort Order Without Affecting Category Pages
Changing the default sort order for search results is a common request in Magento development projects. While there are several articles online that guide you through this process, they often lead to an unwanted side effect - changing the sort order on category pages as well.
In this post, we’ll explore how to modify your Magento instance so that search results are sorted by a specific attribute (in this case, part number), while keeping category pages sorted by their default “Position” attribute. This approach allows you to maintain the separation between these two distinct functionalities.
Understanding the Problem
The issue arises because the core Magento template files (like catalogsearch/result.phtml) use the same sorting logic for both search and category views. When you modify the sort order, it affects both, leading to the unexpected behavior on category pages.
To resolve this, we’ll need to create a custom extension that overrides the default template file for search results only. This ensures that your changes are applied to the search view without touching the category view logic.
Setting Up Your Custom Extension
First, let’s set up a new module in your Magento instance:
- In your project root directory, navigate to
app/code. - Create a new folder called
Company_SearchSort. - Inside this folder, create another folder called
etcand then an XML file namedmodule.xml.
In the module.xml file, add the following content:
<config xmlns:node="urn:magento:framework:app/code-etc:core_module">
<module name="Company_SearchSort" setup_version="1.0.0">
<sequence>
<module name="Magento_CatalogSearch"/>
</sequence>
</module>
</config>
Replace Company with your actual company name.
This configuration ensures that our custom module is loaded after the core Magento catalog search module, which allows us to override its templates and logic.
Overriding the Search Result Template
Next, let’s create a new block file that will handle the sorting of search results:
- In
Company_SearchSort, create another folder calledBlock. - Inside this folder, create an XML file named
searchresult.php.
In the searchresult.php file, add the following content:
<?php
namespace Company\SearchSort\Block;
use Magento\Framework\View\Element\Template;
class SearchResult extends Template
{
public function getSortedItems()
{
$sortAttribute = 'part_number';
$direction = 'asc';
// Get search results and sort by the specified attribute
$sortedResults = $this->getItems()->getSize() ? $this->getItems()->getItemsByColumnValue('entity_id') : [];
usort($sortedResults, function ($a, $b) use ($sortAttribute, $direction) {
return strcmp($a->getData($sortAttribute), $b->getData($sortAttribute)) * ($direction === 'asc' ? 1 : -1);
});
return array_slice($sortedResults, 0, $this->getItems()->getSize());
}
}
This block file defines a new method called getSortedItems that sorts the search results by the specified part number attribute in ascending order. You can modify these parameters (sortAttribute, $direction) according to your requirements.
Overriding the Search Result Template File
Finally, let’s create an override for the default catalogsearch/result.phtml template file:
- In
Company_SearchSort, create another folder calledviewand then a sub-folder namedfrontend. - Inside this folder, navigate to
templates/catalogsearch. - Create a new PHP file named
result.phtml.
In the result.phtml file, add the following content:
<?php
/** @var \Company\SearchSort\Block\SearchResult $block */
?>
<div class="catalogsearch-results-count">
<span id="search-terms"><?= /* @escapeNotVerified */ $this->getEscapedHtmlAttr($this->helper('Magento\Framework\Data\Tree::getCountLabel')($_productCollectionSize)) ?></span>
</div>
<?php if ($block->hasSortedItems()) : ?>
<?php foreach ($block->getSortedItems() as $_item) : ?>
<div class="search-result-item">
<?= /* @escapeNotVerified */ $this->getProductName($_item) ?>
<?= /* @escapeNotVerified */ $this->getProductPrice($_item) ?>
<!-- Add other necessary details here -->
</div>
<?php endforeach; ?>
<?php endif; ?>
This template file uses the Block\SearchResult class (which we previously created) to fetch and display the sorted search results. It ignores the default sorting logic used in the core template file.
Conclusion
By following this approach, you can successfully modify the sort order for Magento search results without affecting the sort order on category pages. This custom extension provides a clean separation between the two functionalities, allowing you to maintain your desired behavior for each view.
Remember to clear your cache after implementing these changes:
php bin/magento cache:flush
This ensures that the new template and block files are properly loaded in your Magento instance.
For more information on working with custom extensions in Magento, feel free to explore our detailed guide on Magento extension development at Laravel Company.