Default WordPress allows you to display recent posts and recent comments through a widget. However, as I develop my own theme, I want to be able to customize as much as possible without using a widget in my sidebar at all.
The problem is, displaying recent posts and recent comments is not as simple as just using a WordPress template tag found in WordPress Codex. Instead, you will need to get creative and create a bit of custom code to grab the data from the database.
There are definitely some common code snippets used for WordPress but I found the ability to control and display recent posts and recent comments to be what I need most.
Displaying Most Recent Posts
There are several ways to display the most recent posts from just using the wp_get_archives tag to query_posts tag which involves using the WordPress loop. There is a more customized solution that I found from Dino Latoga and its as follows:
<?php
$recentposts = get_posts('numberposts=12&category=4');
foreach ($recentposts as $post) :
setup_postdata($post);
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
Displaying Most Recent Comments
Also from Dino’s post on commonly used WordPress code snippets is being able to display recent comments. Unlike displaying most recent posts, it doesn’t necessarily uses any WordPress tags. Instead, you are actually querying your database to grab the necessary information you want to be displayed.
Here is the code for displaying most recent comments:
<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,30) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =
$wpdb->posts.ID)
WHERE comment_approved = '1' AND comment_type = '' AND
post_password = ''
ORDER BY comment_date_gmt DESC
LIMIT 7";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
$output .= "\n<li>".strip_tags($comment->comment_author)
.": " . "<a href=\"" . get_permalink($comment->ID) .
"#comment-" . $comment->comment_ID . "\" title=\"on " .
$comment->post_title . "\">" . strip_tags($comment->com_excerpt)
."…</a></li>";
}
$output .= "\n</ul>";
$output .= $post_HTML;
echo $output;?>
There a tons of custom codes to make your WordPress installation that much more feature and content rich, but these two code snippets have helped me create a better user experience when combined with Tabbed Menu in the sidebar.