[SOLVED] Randomly display content of one of the first five nodes in the query in a Views block.

| | 1 min read

If your Drupal site has a group of nodes ordered chronologically and you wish to randomly show one of the first five most recent nodes each time then you might face a small roadblock. SQL has no way to do this and therefore there is no way Views can execute this directly. However there is a workaround to make this work. Read onto find out more.

Here is the recommended method to get this working on your View

  • First configure your View to return the first 5 results.
  • Next you have to write a hook_views_post_execute() hook in your custom module.
  • In that hook take $view->result and reduce it to just one result randomly with a piece of PHP code similar to the one as follows
  •        result = array($view->result[array_rand($view->result)]);

Hope that helps.

The easiest way to solve a Drupal issue is to hand it to the Drupal experts. Do you need professional help in building your Drupal site? We can provide a wide range of Drupal services to help you deploy your Drupal site easily and quickly. Get in touch with us to know more.