Codeable info

Make a Recently Commented Posts Short Code

Posted on by in WordPress Tutorials

A popular way for sites to display their most-talked-about posts, or those with recent commentary, is to have a widget that displays a list of the 5 or ten latest comments, and the posts that received the comments. There are several plugins that do this for you, but it’s always useful to know how to do it on your own.

We’re going to write two functions, one that queries the posts, and one that taps into the first function through a short code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function posts_by_comments($no_posts = 10) {
    global $wpdb;
 
	$sql = "SELECT ID, post_title, post_content, post_excerpt FROM $wpdb->posts JOIN $wpdb->comments ON $wpdb->posts.ID=$wpdb->comments.comment_post_ID WHERE comment_ID IN (SELECT MAX(comment_ID) FROM $wpdb->comments WHERE comment_approved = '1' AND comment_type='' AND comment_post_ID = $wpdb->posts.ID GROUP BY comment_post_ID) AND post_status ='publish' AND post_type='post' AND post_password ='' ORDER BY comment_ID DESC LIMIT $limit";	
 
	$commented_posts = $wpdb->get_results($sql);
 
	if ($commented_posts) { 
		echo '<ul>';
			foreach ($commented_posts as $p) {
				ob_start();
				$the_post = get_post($p->comment_post_ID);
				?>	
				<li>
						On <?php echo &#039;<a>comment_post_ID) . '">' . get_the_title($p->comment_post_ID) . '</a>'; ?> by
						comment_author; ?>: 
						comment_ID); ?>
				</li>
				<?php
				ob_end_flush();
		echo '</ul>';
	}
}

This function will query the database and find the 10 (by default) latest commented on posts and display them in an unordered list.

Now, we need to write a function that will add our shortcode.

1
2
3
4
5
6
7
8
9
10
function posts_by_comments_shortcode( $atts, $content = null )
{
	extract( shortcode_atts( array(
      'number' => 10
      ), $atts ) );
 
	return posts_by_comments($number);
 
}
add_shortcode('posts_by_comments', 'posts_by_comments_shortcode');

You will now be able to use a shortcode like this:

[posts_by_comments number=5]

Comments Closed

Codeable info