Random sorting with search API in Drupal 7 | NDP

Main content

Random sorting with search API in Drupal 7

Every now and then you get asked to order view results randomly. This is good as it keeps the content new and content right at the bottom of the index will get a chance to shine.

The Problem

Views in Drupal has this functionality built in, you can add Global: Random for your search criteria.



However, this doesn’t work for a view which is listing indexed data from search api.

The solution

There are/could be modules to fix this behavior, but here is a nice trick to get some really random ordering…

Add a field to the content type(s) you are indexing… we will call this field ‘Sort Order’, and for example sake the content type will be ‘Blog post’. Now in a hook_node_presave() we will assign the value of this field. (I’m assuming you know how to add a custom module with a hook in it, but if not, please comment). Our hook will look like this:

Note that you will obviously need to change ‘search_api_random’ to your module name and ‘blog_post’ to your content type being indexed.

   * Implements hook_node_presave(). 
   * Assigns a random number for sorting search api

function nmg_glue_node_presave($node) {
  if ($node->type == 'product_display' || $node->type == 'customisable_product_display' && empty($node->field_sort_number[LANGUAGE_NONE][0]['value'])) { $node->field_sort_number[LANGUAGE_NONE][0]['value'] = rand(); 


What this small snippet is doing is assigning a random number as the value on the node when it’s saved. As a little-added niceness, there is a condition to check if the sort field is empty, so if you wanted to place something on the first page you could assign your own value of ‘1’.

Now all that’s left to do is configure our view with our new sort criteria:



Take aways

You’ll find an example module on GitHub here

Contact Us

Send us a project outline or brief, and we'll contact you.

Click here