Magento – Magento 2 – catalog product list widget product order

magento2product-listwidget

The homepage of my magento website is showing a product list. This product list was made with the catalog product list widget configured to show the products which are in the homepage category. Products in this category have a position number. Products are displayed in what seems to be price ordered list. How do I get the widget to display position ordered list ?

Best Answer

If you want order by position in the widget product list, you must do the next.

Namespace/CustomWidgets/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\CatalogWidget\Block\Product\ProductsList">
        <plugin name="custom_widgets_product_list" type="Namespace\CustomWidgets\Plugin\Block\Product\ProductsListPlugin"/>
    </type>
</config>

Namespace/CustomWidgets/Plugin/Block/Product/ProductsListPlugin.php

<?php    
namespace Namespace\CustomWidgets\Plugin\Block\Product;

use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\CatalogWidget\Block\Product\ProductsList;

/**
 * Class ProductsListPlugin
 */
class ProductsListPlugin
{

    /**
     * @param ProductsList $subject
     * @param Collection $result
     * @return Collection
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterCreateCollection(ProductsList $subject, Collection $result)
    {
        $result->getSelect()->order('cat_index_position asc');

        return $result;
    }
}

This order is always by the position of the root category. If you want order by a specific category, you must create a new custom widget for that.

Related Topic