Skip to main content

How to Add Magento 2 Sort by Price for Low to High & High to Low Options and name A-Z & Z-A etc sort dropdown

The store design and its navigation must be in such a way that makes it easier for the shopper to find the exact required product and make the shopping process comfortable and enjoyable.  Navigation can be made easier and hence improve the shopping experience by offering custom sorting options.

The default Magento 2 offers sorting by position, product name, and price

 A price-sensitive customer may save some clicks by starting with the cheapest products. On the other hand, customers who have a high standard for quality may quickly find their most desired products by sampling from high prices to low prices. To provide such feature in Magento 2 and serve both the type of price-sensitive customers, you can add Magento 2 sort by price for low to high & high to low options.

Some people can sort by names A-Z or Z-A, position low to high high to low like this we can improve sales to our site and user can easily find products

for implementing this fallow given steps to implement sorting

Adding sorting options::

1.Create registration.php file in app\code\Pawan\Customsort\

<?php
        \Magento\Framework\Component\ComponentRegistrar::register(
            \Magento\Framework\Component\ComponentRegistrar::MODULE,
            'Pawan_Customsort',
            __DIR__
        );

2.Create module.xml file in app\code\Pawan\Customsort\etc

    <?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="Pawan_Customsort" setup_version="1.0.0"/>
    </config>

3.Create di.xml file in app\code\Pawan\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="Pawan_Customsort::addCustomOptions" type="Pawan\Customsort\Plugin\Model\Config" />
    </type>
    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="Pawan_Customsort::addPriceDecendingFilterInToolbar" type="Pawan\Customsort\Plugin\Product\ProductList\Toolbar" />
    </type>
</config>


4.Create Config.php file in app\code\Pawan\Customsort\Plugin\Model

<?php
namespace Pawan\Customsort\Plugin\Model;

use Magento\Store\Model\StoreManagerInterface;

class Config  {


    protected $_storeManager;

    public function __construct(
        StoreManagerInterface $storeManager
    ) {
        $this->_storeManager = $storeManager;
    }


    public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig, $options)
    {
        $store = $this->_storeManager->getStore();
        $currencySymbol = $store->getCurrentCurrency()->getCurrencySymbol();
        
        
//        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/logfile.log');
//        $logger = new \Zend\Log\Logger();
//        $logger->addWriter($writer);
//        $logger->info('Simple Text Log'); // Simple Text Log
//        $logger->info('Array Log'.print_r($store, true)); // Array Log
        
        // Remove specific default sorting options
        $default_options = [];
        $default_options['name'] = $options['name'];

        unset($options['position']);
        unset($options['name']);
        unset($options['price']);
        

        //Changing label
        $customOption['position_asc'] = __('Position low to high');
        $customOption['position_desc'] = __('Position high to low');
//        $customOption['position'] = __( 'Position' );
        $customOption['name_asc'] = __('Name A-Z');
        $customOption['name_desc'] = __('Name Z-A');
        
        $customOption['price_asc'] = __('Price low to high');
        $customOption['price_desc'] = __('Price high to low');
        
       
        
        //New sorting options
        //$customOption['created_at'] = __( ' New' );


       // $customOption['name'] = $default_options['name'];

        //Merge default sorting options with custom options
        $options = array_merge($customOption, $options);
//        $logger->info('Array Log'.print_r($options, true)); // Array Log
        return $options;
    }
}



5.Create Toolbar.php file in app\code\Pawan\Customsort\Plugin\Product\ProductList

<?php
namespace Pawan\Customsort\Plugin\Product\ProductList;

class Toolbar
{

    public function aroundSetCollection(
        \Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
        \Closure $proceed,
        $collection
    ) {
        $currentOrder = $subject->getCurrentOrder();
        $result = $proceed($collection);

//        if ($currentOrder) {
//            if ($currentOrder == 'position_asc') {
//                $subject->getCollection()->setOrder('position', 'asc');
//            }elseif ($currentOrder == 'position_desc') {
//                $subject->getCollection()->setOrder('position', 'desc');
//            } elseif ($currentOrder == 'name_asc') {
//                $subject->getCollection()->setOrder('name', 'asc');
//            } elseif ($currentOrder == 'name_desc') {
//                $subject->getCollection()->setOrder('name', 'desc');
//            }
//        }
//        return $result; 
        
        switch ($currentOrder) {
            
            case "position_asc":
                $subject->getCollection()->setOrder('position', 'asc');
                return $result;
            case "position_desc":
                $subject->getCollection()->setOrder('position', 'desc');
                return $result;
                
            case "name_asc":
                $subject->getCollection()->setOrder('name', 'asc');
                return $result; 
            case "name_desc";
                $subject->getCollection()->setOrder('name', 'desc');
            return $result; 
            case "price_asc":
                $subject->getCollection()->setOrder('price', 'asc');
                return $result; 
            case "price_desc";
                $subject->getCollection()->setOrder('price', 'desc');
                return $result; 
            
                
            default:
               $subject->getCollection()->setOrder('position', 'asc'); 
             return $result;   
        }

        
    }
}


The above method is just right to improve the sorting and offer options to sort the products
you can able to see like below

      
                     

Comments

Popular posts from this blog

magento 1 extension converted in to magento 2 process

Simple Install =================================== Download as a zip below link. unzip and upload it to your public_html or other rootdoc directory. https://github.com/magento/code-migration. login to your server via shell switch to the code-migration-develop directory by running following command   cd code-migration-develop Run command following command in root directory of this toolkit composer instal Before running the migration, the following directories need to be prepared: ===================================== * `<src>` - Directory that contains custom Magento 1.x code that is intended to be migrated. The code must follow the Magento 1.x directory structure.   Magento1.x core files must not be included. * `<dst>` - Empty directory for the toolkit to put the generated Magento 2 code to * `<m1>` - Directory that contains: * Vanilla Magento 1.x codebase, and * Custom Magento 1.x code same as...

Magento 2 product collection Filtering multi-select attribute values

  If you have multi-select attribute of product like below If you want filter value for this option Use below syntax to get product data: ->addAttributeToFilter('store_model', array('finset' => $params['store_model'])) finset key is used for multiselect attribute filter. $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $products = $objectManager->get('Magento\Catalog\Model\Product')         ->getCollection()         ->addAttributeToSelect('*')         ->addAttributeToSelect('store_brand')         ->addAttributeToSelect('store_model')         ->addAttributeToSelect('store_year')         ->addAttributeToFilter('store_brand', array('finset' => $params['store_brand']))         ->addAttributeToFilter('store_model', array('finset' => $params['store_model']))         ->ad...

Magento Debug HEADERS ALREADY SENT error

When you  receiving the following error in  system.log file: app\code\core\Mage\Core\Controller\Response\Http.php:44  [1] \www.pawan.com\lib\Zend\Controller\Response\Abstract.php:727  [2]  \www.pawan.com\app\code\core\Mage\Core\Controller\Response\Http.php:75  [3]  \www.pawan.com\app\code\core\Mage\Core\Controller\Varien\Front.php:188  [4]  \www.pawan.com\app\code\core\Mage\Core\Model\App.php:304  [5]  \www.pawan.com\app\Mage.php:596  [6]  \www.pawan.com\index.php:81 if you have no idea what file is causing this. Here is the steps to debug. That error is thrown from Mage_Core_Controller_Response_Http -> sendHeaders(). This function calls the super class function that actually does the check to see whether or not headers have already been sent, Zend_Controller_Response_Abstract -> canSendHeaders(). The Zend_Controller_Response_Abstract class handles, among other things, sending response header...