0

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?

1 Answer 1

3

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');
2
  • Unfortunately, this doesn't seem to work. Adding the code (and clearing caches) makes no difference to the order of the products, which seems to be arbitrary rather than by title, ID, etc.
    – Geat
    Mar 1, 2017 at 19:21
  • Oh, sorry. It IS working - the array of product Ids is in the correct order. My code for outputting those products from the array is going wrong somewhere. Thank you!
    – Geat
    Mar 1, 2017 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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