WordPress Get Recent Posts And Recent Comments
Posted by in PHP April 17, 2012 2 Comments

In this article, I’ll show pieces of PHP script that retrieve and display Recent/Latest Published Posts and Recent/Latest Approved Comments. They’re being used in my current WordPress template and placed in the footer.

There are some plugins and widgets on the internet that retrieve and display recent posts and comments but for some simple functions like these, I recommend that you should do it by yourself. By doing this, we can fully understand what’s happening behind the scene, fully control their appearance and easily place them into wherever you want (footer, sidebar, etc).

1. Get And Display Recent Published Posts

The PHP code below simple get top 5 of recent published posts by using WordPress wp_get_recent_posts function. You can change the number of returned post by adjusting the numberposts variable.

<div class="block" style="border-right: #42475b 1px solid; border-left: #000 1px solid;">
	<div style="padding: 0px 60px;">
		<span class="tittle">Recent Posts</span>
		<ul>
<?php
$args = array( 'numberposts' => '5', 'post_type' => 'post', 'post_status' => 'publish');
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
}
?>
		</ul>
	</div>
</div>

2. Get And Display Recent Approved Comments

The PHP code below retrieves and displays top 5 of recent approved comments. In many plugins/widgets, they will display the comment author’s URL (comment_author_url) but I don’t because some many guys are trying post comments for back link purpose.

<?php
<div class="block" style="border-right: #42475b 1px solid;">
	<div style="padding: 0px 60px 0 0;">
		<span class="tittle">Recent comments</span>
		<ul>
<?php
global $wpdb;
$sql = "
SELECT DISTINCT ID, post_title, comment_ID, comment_post_ID, comment_author, comment_type,comment_author_url
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 5";
$comments = $wpdb->get_results($sql);
 
foreach ($comments as $comment) {
echo "<li><span style='color: #666666;'>" . strip_tags($comment->comment_author) . " on </span>" . "<a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"on " . $comment->post_title . "\">" . strip_tags($comment->post_title) ."</a></li>";
}
?>
		</ul>
	</div>
</div>
?>

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • CJ

    Niceeeeeee

  • http://www.rayban3025.uk.com/ ray ban 3025

     Very useful!!! Especially the comments show!!!!
    Wish you love ray ban 3025 !!