I have created a custom sorting option distance in magento 2.4.3-p1 and sort the collection with custom sorted entity ids


`<type name="Magento\Catalog\Model\Config">
    <plugin name="catalog_config_plugin" type="Sunarc\NearByProduct\Plugin\Config" />
<preference for="Magento\Catalog\Block\Product\ProductList\Toolbar" type="Sunarc\NearByProduct\Block\Catalog\Product\ProductList\Toolbar" />

<type name="Magento\Elasticsearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolver">
    <plugin name="ajourquin_unset_es_order" type="Sunarc\NearByProduct\Plugin\Elasticsearch\Model\ResourceModel\Fulltext\Collection\SearchCriteriaResolver" />


public function afterGetAttributeUsedForSortByArray(\Magento\Catalog\Model\Config $catalogConfig,$results)
    $results['distance'] = __('Distance');
    return $results;


public function afterResolve(MagentoSearchCriteriaResolver $subject, SearchCriteria $result): SearchCriteria
    $sortOrders = $result->getSortOrders();
    return $result;


$ids = array(4,5,2,1,3);
$ids = implode(',',$ids);
$this->_collection->getSelect()->order(array(new \Zend_Db_Expr("FIELD(e.entity_id, " . $ids . ")")));
 foreach($this->_collection as $data)

Here before foreach collection is sort with entity id 4,5,2,1,3 properly, but when we in the foreach loop $data->getData() give the product in 1,2,3,4,5 entity_id order, and also print query show correct field order 4,5,2,1,3.Because of this products are not showing with sort order on storefront.

Any one tell me what is the issue or any other things which i have missed. Any help is appriciated.

  • Please tell me you solved this problem. I have exactly the same right now. Commented Mar 25 at 11:05

1 Answer 1


If think you just need to save the sorted collection and iteration over that one.

$this->_collection->getSelect()->order(array(new \Zend_Db_Expr("FIELD(e.entity_id, " . $ids . ")")));

Replaced by

$sortedCollection = $this->_collection->getSelect()->order(array(new \Zend_Db_Expr("FIELD(e.entity_id, " . $ids . ")")));

Then for foreach on sortedCollection.

That being said, this is not how you should sort a collection in magento

This is the way

    $productCollection = $this->productCollectionFactory->create();
  • Thanks but distance is not a product attribute, it's only a option on storefront in sort by option dropdown Commented Aug 12, 2022 at 10:56
  • I have only $ids = array(4,5,2,1,3); Commented Aug 12, 2022 at 11:05

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.