Sorting Magento Layered Navigation Filters by Item Count
As an e-commerce developer, you may often find yourself wanting to sort your store’s layered navigation filters based on the number of items in each category. In this post, I’ll guide you through sorting your Magento layered navigation filters by count using a straightforward approach.
Understanding the Default Behavior
By default, Magento displays layered navigation filters alphabetically. This can sometimes lead to an odd ordering that doesn’t provide the best user experience:
- Books - 1
- CD's - 2
- DVD's - 20
To improve this, we want to sort the filters by the number of associated items in descending order.
Sorting Magento Collections
In Magento, collections are used to interact with database records. To sort a collection, you can use the order method. However, sorting directly within the layered navigation template isn’t recommended due to performance and code organization concerns.
A better approach is to modify your filter model’s getItems() function to return sorted items based on their count:
<?php
namespace Magento\LayeredNavigation\Model\Filter;
class Filter extends \Magento\Framework\Model\AbstractModel implements \Magento\LayeredNavigation\Api\Data\FilterInterface
{
public function getItems()
{
$collection = $this->getResource()->getItems($this->_entityId);
$collection->order('count', 'desc');
return $collection;
}
}
In this code snippet, we’re overriding the getItems() method of the filter model. We first fetch the items using the existing resource getter and then sort them by their count in descending order using the order method.
Reindexing After Changes
After making these changes to your filter models, you’ll need to reindex your catalog data for the updates to take effect:
- Open Magento’s admin panel.
- Navigate to Stores > Index Management.
- Select Reindex All or specifically reindex the Catalog Category Flat Data.
Conclusion: Enhancing Layered Navigation UX
Sorting layered navigation filters by item count provides a better user experience, helping customers quickly find what they’re looking for based on relevance rather than alphabetical order.
Remember to keep your customizations well-documented and separate from core Magento files, especially if you plan to update the platform in the future. This approach ensures a clean upgrade path and prevents potential conflicts.
For more advanced layered navigation customization techniques, I recommend checking out our comprehensive guide on Magento 2 Layered Navigation Extensions & Customization. The post provides an in-depth look at extending Magento’s built-in layered navigation functionality.
Happy coding!