0

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();
                }
            }

    }

1 Answer 1

1

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.

5
  • thanks @Gideon. I removed name option by your code but price (High to Low) didn't sort correctly. I use default price for Low to High but what can i do for High to Low?!
    – Benyo
    Commented Jul 3, 2018 at 11:27
  • sorry. i upvoted your answer but i don't have enough reputation yet
    – Benyo
    Commented Jul 3, 2018 at 11:40
  • High to low and low to high is working for me. Please check my Toolbar file here: gist.github.com/GideonBabu/143ad54de27ea7d3997e294fea14b498 Commented Jul 3, 2018 at 12:35
  • thanks @Gideon. i found a solution here : magento.stackexchange.com/questions/149125/…
    – Benyo
    Commented Jul 3, 2018 at 13:23
  • @Benyo I am glad you got the solution. Commented Jul 3, 2018 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.