How to Sort after position a product collection?
-
29-09-2020 - |
Question
This is how I get my collection:
$_productCollection = $this->getItemCollection();
This is how I get the products:
foreach ($_productCollection as $_product):
echo $_product->getData('position');
endforeach
At the moment I get my products randomly. Can I sort by position ? if yes how can i do it ? thx
This is the getItemCollection function from CORE:
public function getItemCollection()
{
if (is_null($this->_items)) {
$behavior = $this->getPositionBehavior();
$this->_customItems = array();
$this->_items = array();
if (in_array($behavior, $this->getRuleBasedBehaviorPositions())) {
$this->_items = $this->_getTargetRuleProducts();
}
if (in_array($behavior, $this->getSelectedBehaviorPositions())) {
foreach ($this->_getLinkProducts() as $id => $item) {
$this->_customItems[$id] = $item;
}
}
$this->_orderProductItems();
}
return $this->_items;
}
Solution
Not possible, because this method does not return a collection (bad naming choice...). Instead it loads the collection immediately and returns an array with the results.
The simplest solution is to sort this array, using PHP:
usort($_productCollection, function($a, $b) {
if ($a['position'] < $b['position]) {
return -1;
} elseif ($a['position'] > $b['position']) {
return 1;
}
return 0;
});
or if you are using PHP 7:
usort($_productCollection, function($a, $b) {
return $a['position'] <=> $b['position'];
});
OTHER TIPS
Ok so you're talking about sorting and not filtering.
To do so you can use the setOrder
method:
$_productCollection->getSelect()->order('position DESC');
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange