Adding a "Sort By" option in Magento 2 can improve the user experience by allowing customers to organize products based on their preferences. Here's a step-by-step guide to Magento 2 add sort by option:
Directory Structure:
Create a new directory structure for your module:
app/code/Vendor/CustomSort
module.xml:
Create the module.xml file in app/code/Vendor/CustomSort/etc/ and add the following content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_CustomSort" setup_version="1.0.0"/>
</config>
registration.php:
Create the registration.php file in app/code/Vendor/CustomSort/:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Vendor_CustomSort',
__DIR__
);
DefaultSorting.php:
Create DefaultSorting.php in app/code/Vendor/CustomSort/Plugin/ to add your logic:
<?php
namespace Vendor\CustomSort\Plugin;
class DefaultSorting {
public function afterGetAvailableOrders(\Magento\Catalog\Model\Config $subject, $result) {
$result['custom_sort'] = __('Custom Sort');
return $result;
}
}
Modify di.xml:
Create or modify di.xml in app/code/Vendor/CustomSort/etc/:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Model\Config">
<plugin name="vendor_custom_sort" type="Vendor\CustomSort\Plugin\DefaultSorting" />
</type>
</config>
Enable the Module:
Run the following command in the terminal:
php bin/magento module:enable Vendor_CustomSort
php bin/magento setup:upgrade
php bin/magento cache:flush
Test It:
Go to your Magento 2 store's product listing page to see the new "Custom Sort" option in the dropdown, enhancing your Magento 2 sort by options.
To unlock even more sorting options and improve your store further, consider trying our Improved Sorting for Magento 2 extension.
Login and Registration Form