Sorting Cross-Sell Products in Magento 2.1
-
06-10-2020 - |
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?
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