How to Sort Magento 2 Layered Navigation Attributes Programmatically
The following post is a solution for the order of the attributes in layered navigation on the category list page.
For example, you want to change the sorting in 1-9 and a-z of the layered navigation attributes on the category page. The sole purpose of this sorting is to ease the search of the users and provide them with better user experience. Let’s understand this with an example: If you have a store selling mobile phones of the various brands and you have enabled the brand options in the layered navigation. Showing the brand name in sorting order makes it easy for the users to select and filter the mobile phones of the specific brands.
If the attribute does not have a custom source it uses default source class which is \Magento\Eav\Model\Entity\Attribute\Source\Table
The function attributeOptionCollection is created on which a function setPositionOrder($dir, $sortAlpha) is called and all the attribute options are returned in this function.
In this function, I have hardcoded sort order of the options collection – $this->setOrder(‘main_table.sort_order’, $dir);
To make the function work as you want, there are two methods as below to sort Magento 2 layered navigation attributes programmatically :
Methods to Sort Magento 2 Layered Navigation Attributes Programmatically:
- Create a before plugin on \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::setPositionOrder
- Change the $sortAlpha variable to true to sort alphabetically.
- Create and around/after plugin on \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::setPositionOrder to sort the way you want.
Implement any of the above methods as per your requirements.
For example, the following image shows the alphabetical sorting in the layered navigation:
You may use the Comments section below to mention any doubts and I’d be happy to help!
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Get Magento 2 URL in JS File
How to Create Console Command in Magento 2
Next