Skip to content

Instantly share code, notes, and snippets.

@schnippy
Last active September 23, 2019 18:31
Show Gist options
  • Save schnippy/b4d018d2b518f54698538aefeb708c0d to your computer and use it in GitHub Desktop.
Save schnippy/b4d018d2b518f54698538aefeb708c0d to your computer and use it in GitHub Desktop.
Drupal 7: Create menu_hook to load random node of approved content types for more efficient debugging and testing

Drupal 7: Create menu_hook to load random node by type

On many projects, I often have a need to be able to see a random node of a particular content type for debugging or load testing. I use this function on Drupal 7 sites in my core module / feature to add a hook of:

http://mysite/random/my-content-type

(I use this instead of a view sorted by random because I want to be redirected to the full path of the node.)

Leaving off the content-type will use a random type from the array of valid content types I have provided. Providing an invalid content type will redirect it to an item from my core (or default) content-type.

* Implement hook_menu().
*/
function my_module_menu() {
  $items = array();

  $items['random'] = array(
    'page callback' => 'my_module_random_node',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Selects random node of passed content type from /random/<type> and redirects to node
 */
function my_module_random_node($type = "default_type") {
  // sanitize incoming text from callback hook
  $type = check_plain(strtolower($type));

  // build an array of valid content type machine names
  $valid_types = array("page","default_type");

  // If no type selected (ex. /random), select a random type from above list 
  if (!$type) { $tmp = array_rand($valid_types); $type = $valid_types[$tmp]; }

  // If type is invalid, send them to the default_type 
  if (!in_array($type,$valid_types)) { $type = "default_type; }

  // load random nid and redirect using drupal_goto
  $nid = db_query("SELECT nid FROM node WHERE type = :type and status=1 order by RAND() limit 0,1", array(':type' => $type))->fetchField();
  drupal_goto("node/".$nid);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment