0

I need to sort the product collection in category page by a custom attribute inventory_status. The attribute is of type int. I need to add the sort with the existing sorting applied.

For example, if the products are sorted according to Bestseller, then there is already an ORDER BY in the collection query. With this order by, I need to add another order by according to inventory_status

I created a before plugin on load method of Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection but here the custom attribute is not coming in the select query.

public function beforeLoad(\Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection $subject, $printQuery = false, $logQuery = false)
{
    // $orderBy = $subject->getSelect()->getPart(\Zend_Db_Select::ORDER);
    $outOfStockOrderBy = array('inventory_status ASC');
    /* reset default product collection filter */
    $subject->getSelect()->order($outOfStockOrderBy);

    return [$printQuery, $logQuery];
}

Edit:

The custom attribute values are coming for each product, but adding the sort order according to the custom attribute is not changing the product results. There is already sorting applied to the products based on bestseller attribute.

0

I used a before plugin on \Magento\Catalog\Block\Product\ProductList\Toolbar::setCollection() and it worked.

So I changed my plugin code to following with the method and it worked

public function beforeSetCollection(
        \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar,
        $collection
) {
        $collection->setOrder('inventory_status', 'asc');
        return [$collection];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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