A block to show random content titles for Drupal
Do you like my Random Content block? I thought it would be nice to show people random selections from previous entries on my website as another way, along with the Popular Content block, to help visitors discover pages that they might be interested in. The way it was done is a little hack-ish, and it would be better to write this up as a module, but it does give an example of a custom content block using the PHP filter. The method I have used us to pick two node ids at random from the database (change the LIMIT statement if you want more) using a MySQL trick (I guess this won't work on Postgres), that is to use a ORDER BY RAND() statement to mix up the rows in our SELECT query and a LIMIT statement to select how many we want. After that it is a case of using the node_load() function in the Drupal API to load up the details. The code for all of this is shown below.
<div class="item-list">
<ul>
<?php
$sql = "SELECT nid FROM `node` WHERE `type` = 'blog' AND `promote` = 1 ORDER BY RAND() LIMIT 0,2";
$results = db_query($sql);
while ($data = db_fetch_object($results)) {
$node = node_load($data->nid);
echo "<li>".l($node->title, $node->path)." (".format_date($node->created, 'custom', "d M Y").")</li>";
}
?>
</ul>
</div>
Trackback URL for this post:
- Liam Green-Hughes's blog
- 1811 reads





















Comments
Re: A block to show random content titles for Drupal
It doesn't seem to link to the right page though, but the home page?
Re: A block to show random content titles for Drupal
Hi Alan,
You'll need the Pathauto module to make this work as is (whoops should have mentioned that really!). Without the module you'll get no value for $node->path, which in a browser will mean that you just get a link to the home page. You can make this work without the Pathauto module by changing the line that outputs the link to:
echo "<li>".l($node->title, 'node/'.$node->nid)." (".format_date($node->created, 'custom', "d M Y").")</li>";
Hope this helps.
Post new comment