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:

About these ads

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

  1. Pingback: implementing addtag in drupal template | Code and Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s