Drupal: Custom Latest Posts

We’re currently developing a Drupal community website for an up-and-coming society.

On the community front page we wanted to display a list of the most recent forum posts. This can easily be accomplished using the Drupal API, and the forum_block() function, with the parameters ‘view’, and the 0 for most active posts, and 1 for newest post (i.e. forum_block(‘view’,0).

The problem in our situation was that we wanted to be able to customize the output beyond the standard API capabilities. In this case, it is a small customization, but this small customization involved digging deep into the Drupal PHP code. We wanted to display who posted the forum topic.

Here’s what we did:

<?php

/*Display Most Active Forum Posts*/

//sets variable to display 3 most active posts
variable_set(‘forum_block_num_0’, ‘3’);

//SQL databse call, copied from forum_block(), added: n.uid which is the database value storing the user id of the poster
$sql = db_rewrite_sql(“SELECT n.nid, n.title, n.uid, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND n.type = ‘forum’ ORDER BY l.last_comment_timestamp DESC”);

//Get database results, and limit to number of posts defined by forum_block_num
$result = db_query_range($sql, 0, variable_get(‘forum_block_num_0’, ‘5’));

//if the result isn’t empty, display the forum topics
if (db_num_rows($result)) {

     //for every row in the database, display the desired output
     while ($node = db_fetch_object($result)) {

           //create a user object, with the uid from the posting
           $user->uid = $node->uid;

           //take the partial user object, load a full user object, and get the username
           $user_name = user_load($user)->name;

           //create a link to the forum node, add ‘posted by’ with poster’s username
           $items[] = l($node->title, ‘node/’. $node->nid, $node->comment_count ? array(‘title’ => format_plural($node->comment_count, ‘1 comment’, ‘@count comments’)) : ”).’ posted by: ‘.$user_name;
     }

//format the resulting list and return as content
     $content = theme(‘node_list’, $items, $title);
}
echo $content; //return the formatted list of recent topics
?>