Magento – Magento 2 sort options

magento2magento2.2

I used Magento 2 add Sort By Best Sellers Option on category products litsing page and Magento 2 Sort by New Products and Most View Product for sorting options. now I want to add price (high to low) and remove name (default option) and direction switcher. Could anyone help me please?

here is my code :

Company\Module\Model\Config

class Config extends \Magento\Catalog\Model\Config
{
    public function getAttributeUsedForSortByArray()
    {
       $options = ['mostviewed' => __('Most Viewed'), 'newest' => __('Newest'), 'bestseller' => __('Best Seller'), 'price' => __('Price - Low To Highا');
        foreach ($this->getAttributesUsedForSortBy() as $attribute) {
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute\AbstractAttribute */
            $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
        }

       return $options;
    }
}

Company\Module\Block\Product\ProductList\Toolbar

class Toolbar extends \Magento\Catalog\Block\Product\ProductList\Toolbar
    {
        public function setCollection($collection)
        {
            if($this->getCurrentOrder()=="bestseller")
            {
                  $collection->getSelect()->joinLeft( 
                    'sales_order_item', 
                    'e.entity_id = sales_order_item.product_id', 
                    array('qty_ordered'=>'SUM(sales_order_item.qty_ordered)')) 
                    ->group('e.entity_id') 
                    ->order('qty_ordered '.$this->getCurrentDirectionReverse());
            }
            if($this->getCurrentOrder() == "newest")
            {
                $collection->getSelect()
                    ->order('created_at ' . $this->getCurrentDirectionReverse());
            }
            if($this->getCurrentOrder() == "mostviewed")
            {
                $collection->getSelect()->joinLeft(
                    'report_event',
                    'e.entity_id = report_event.object_id',
                    array('view_count' => 'COUNT(report_event.event_id)'))
                    ->group('e.entity_id')
                    ->order('view_count ' . $this->getCurrentDirectionReverse());
            }

            $this->_collection = $collection;

            $this->_collection->setCurPage($this->getCurrentPage());

            $limit = (int)$this->getLimit();
            if ($limit) {
                $this->_collection->setPageSize($limit);
            }
            if ($this->getCurrentOrder()) {
                $this->_collection->setOrder($this->getCurrentOrder(), $this->getCurrentDirection());
            }
            return $this;
        }

        public function getCurrentDirectionReverse() {
                if ($this->getCurrentDirection() == 'asc') {
                    return 'desc';
                } elseif ($this->getCurrentDirection() == 'desc') {
                    return 'asc';
                } else {
                    return $this->getCurrentDirection();
                }
            }

    }

Best Answer

For price high to low, add a condition like this in your Company\Module\Block\Product\ProductList\Toolbar file and setCollection function:

if($this->getCurrentOrder()=="high_to_low"){
{
    $this->_collection->setOrder('price', 'desc');
}
if($this->getCurrentOrder()=="low_to_high"){
    {
        $this->_collection->setOrder('price', 'asc');
    }

and you should have a plugin to override config and it should look like this:

Company\Module\Plugin\Catalog\Model

<?php
namespace Company\Module\Plugin\Catalog\Model;

class Config
{
    public function afterGetAttributeUsedForSortByArray(
    \Magento\Catalog\Model\Config $catalogConfig,
    $options
    ) {
        //Remove specific default sorting options(if require)
        unset($options['position']);
        unset($options['name']);
        unset($options['price']);

        //New sorting options
        $newOption['mostviewed'] = __('Most Viewed');
        $newOption['newest'] = __('Newest');
        $newOption['bestseller'] = __('Best Seller');
        $newOption['high_to_low'] = __('Price - High To Low');
        $newOption['low_to_high'] = __('Price - Low To High');

        //Merge default sorting options with new options
        $options = array_merge($newOption, $options);

        return $options;
    }

}

Since we have a plugin, we need to add it in the di.xml file like this under etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Block\Product\ProductList\Toolbar" type="Company\Module\Block\Product\ProductList\Toolbar" />    
    <type name="Magento\Catalog\Model\Config">
        <plugin name="Company_CustomSorting_model_config" type="Company\Module\Plugin\Catalog\Model\Config" />
    </type>
</config>

To remove the direction switcher, you can remove it using CSS/jQuery that should be simple to select the div element and add display none class in css or add remove jquery function.

I hope this helps.

Related Topic