Question

If I retrieve the cross-sell products for a particular product:

$_product->getCrossSellProductCollection();

How do I sort those products in the same order as the administrator has defined via the admin interface?

Was it helpful?

Solution

getCrossSellProductCollection returns instance of Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection

This collection implements following method:

public function setOrder($attribute, $dir = self::SORT_ORDER_ASC)
    {
        if ($attribute == 'position') {
            return $this->setPositionOrder($dir);
        } elseif ($attribute == 'attribute_set_id') {
            return $this->setAttributeSetIdOrder($dir);
        }
        return parent::setOrder($attribute, $dir);
    }

So you should be able to sort the collection similar to admin by calling:

$_product->getCrossSellProductCollection()->setOrder('position');
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top