Drupal 7 – Order EntityFieldQuery by random using hook_query_TAG_alter()

The EntityFieldQuery does not support any method to select the entities by random. A simple workaround is using the query tag and implement the hook_query_TAG_alter().

Add addTag() in your EntityFieldQuery object.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', '<node type>')
  ->propertyCondition('status', 1)
  ->addTag('random')
  ->range(0, 1);


 

Next, add the hook_query_TAG_alter() in your .module file.

/**
 * Implementation of hook_query_TAG_alter
 */
function <module>_query_random_alter($query) {
  $query->orderRandom();
}

 

Please note that it only works when you use the EntityFieldQuery in the .module file.

Done =)

Reference:

6 thoughts on “Drupal 7 – Order EntityFieldQuery by random using hook_query_TAG_alter()”

Leave a reply to tsukassa01 Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.