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>
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.
Re: A block to show random content titles for Drupal
Thanks for the top tip. Have used this on our site, although I would prefer the non-pathauto solution to be given first.
Re: A block to show random content titles for Drupal
This looks like a great solution, but I'm a little confused regarding the actual implementation. I created a custom block using the php filter, but the block content is empty. What am I missing?
Re: A block to show random content titles for Drupal
it's works fine. Thank you.
But i'm added some changes:
print l($node->title, $node->path).'< br />';
print $node->teaser;