Magento – Magento 2 – Product sorting issue on category page using product attribute

category-pagemagento2product-attributesorting

I made product attribute and assign it on of attribute set so that it will show in the admin product detail page. Based on this product attribute I sort the product collection on category page.

The problem is, I set the Catalog Input Type for Store Owner to Text field. I will have to set the numeric value against each product in order to sort the product collection based on this attribute. It works fine from 1-9 but when I increase the count more than 9 like 10, 11 etc it destroy the sorting. It may be because field type is not number type

Any help, experience and knowledge sharing would be appreciated.

Best Answer

Please try following way using custom plugin, so please add plugin code in your custom extension as below

/Vendor/Module/etc/frontend/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">
    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="vendormodule_catalog_block_product_listproduct_toolbar" type="Vendor\Module\Plugin\Catalog\Block\Product\ProductList\Toolbar"/>
    </type>
</config>

/Vendor/Module/Plugin/Catalog/Block/Product/ProductList/Toolbar.php

<?php

namespace Vendor\Module\Plugin\Catalog\Block\Product\ProductList;

class Toolbar
{
    /**
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry;

    public function __construct(\Magento\Framework\Registry $coreRegistry)
    {
        $this->_coreRegistry = $coreRegistry;
    }

    /**
     * @param \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar
     * @param \Magento\Framework\Data\Collection $collection
     * @return array
     */
    public function beforeSetCollection(
        \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar,
        $collection
    ){
        $collection->getSelect()->group('e.entity_id')->order('{YOUR CUSTOM ATTRIBUTE CODE} ASC');
        $collection->getSize();

        return [$collection];
    }
}

Please try and let me know if you get any issue.

Related Topic