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']))         ->ad...

magento 2 best seller product display based on current category and subcategories

Magento 2 getting best seller based on category wise displaying i have done below for that to implement this functionality it is working fine for me. step 1 create block file in our module folder <?php namespace Pawan\Bestseller\Block; use Magento\Catalog\Api\CategoryRepositoryInterface; class Bestsellercategory extends \Magento\Catalog\Block\Product\ListProduct {     /**      * Product collection model      *      * @var Magento\Catalog\Model\Resource\Product\Collection      */     protected $_collection;     /**      * Product collection model      *      * @var Magento\Catalog\Model\Resource\Product\Collection      */     protected $_productCollection;     /**      * Image helper      *      * @var Magento\Catalog\Helper\Image     ...

Magento 2 UI Component Grid Explanation

1) layout file inside Company/Module/view/adminhtml/layout/routerid_controller_action.xml define grid as uiComponent with: 2) uiComponent is defined in Company/Module/view/adminhtml/ui_component/listing_name.xml file. File name must be the same as uiComponent name used in layout file. The structure of the file may seem pretty complex at first sight but as always these are some repeating nodes. To make it simple lets slice it. Main node of the component file is <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">. It is fixed and I believe it requires namespace location attribute. Next there are typically 4 nodes inside <listing /> node: <argument />, <dataSource />, <container /> and <columns />. This is however not a strict setup as <argument /> node might be duplicated to provide more configuration or <container /> as...