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!