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 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']))         ->addAttributeToFilter('store_year', array('

Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous

When trying to filter sales order grid with From and To dates it was redirecting to dashboard.after that again i tried to open sales order grind it is generating reports in reports file it showing. "Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous" means it is finding a another created_at field. because when we adding or joining the other table then it has also a field named as created_at. So below is the  solution for this error. magento that created_at is of the main_table not of my custom table. Find the below code in the sales order grid.php file. $this->addColumn('created_at', array(            'header' => Mage::helper('sales')->__('Purchased On'),             'index' => 'created_at',             'type' => 'datetime',             'width' => '100px',         )); just replace the code with below one.  $this