Eneko Alonso

un Navarro en California

Projects

¿Eres español y vives fuera de España? ¿Estás pensando en salir una temporada a trabajar o estudiar en el extranjero? Si es así, no dejes de visitar Spaniards.es, la Comunidad de Españoles en el Mundo
spaniards.es

Recent comments

18:46 America/Los_Angeles


Adding 'random jump' functionality to your drupal page/blog

It's been a few years I would say since some blogs implemented this random jumping functionality. It is not very useful, but it's fun and sometimes very handy when one is bored. Wikipedia has it, very popular blogs like Microsiervos have it... It is small, simple and fun.

Still I had never used it on my blogs. This morning, don't ask me why, I decided to implement it, which on Drupal becomes a very simple task. Let's see. In order to implement this functionality we need:

  1. A menu link to the random post page
  2. A new page node, which PHP input format

Both tasks are very easy in Drupal, if you are using Primary Links Menus and Page nodes. Now, let's see what the new page node has to do:

  1. Generate a list of published story nodes ids
  2. Pick a random node from the list
  3. Redirect the browser to the randomly selected node page

The two first tasks can be done on a single query using the MySql function Rand(). Also we can limit the query to return only one node. Next we redirect to the new done. Finally, we abort the execution of the page with an exit() call. This will indicate Drupal it doesn't need to keep generating and formatting the new random page, since the user will never see it actually. Here is the code:

$sql = "select nid from {node} where status=1 and type='story' order by rand() limit 0,1"; $result = db_query($sql); if ($anode = db_fetch_object($result)) { global $base_url; header("Location: $base_url/node/$anode->nid"); exit(); } else { print "Error: no node returned."; }

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.