I need to display the products on the search results page in a random order. Since there is no official explanation on how to do this, I tried to edit the Mage_CatalogSearch_Model_Resource_Fulltext
module, but I could't figure out where to add a ORDER BY RAND()
in the prepareResults()
function. Does anyone know how to achieve this?
1 Answer
Ordering actually happens in app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext/Collection.php
You can change ::setOrder()
to look like this in order to always sort randomly – regardless of the sort attribute selected by the user:
public function setOrder($attribute, $dir = 'desc')
{
/* ORIGINAL CODE
if ($attribute == 'relevance') {
$this->getSelect()->order("relevance {$dir}");
} else {
parent::setOrder($attribute, $dir);
}
*/
// RANDOM SORT INSTEAD
$this->getSelect()->getAdapter()->orderRand($this->getSelect());
return $this;
}
Bear in mind that you're changing a core file so for real world code you should consider creating a custom module. You can e.g. listen to the catalog_block_product_list_collection
event and modify the collection sort in an observer if applicable.