In this week’s WordPress Wednesday, we’re going to cover how to display a list of the most commented posts on your blog. This can be a handy way to promote your blog’s more popular content, and encourage further discussion.
To display your blog’s most popular posts, you will first need to create a new query that gets the most commented posts; below, we’re doing this, ordering them in descending order, and limiting the query to eight posts:[php] 'comment_count','order' => 'desc', 'posts_per_page' => '8')); if($most_commented->have_posts() ) : while( $most_commented->have_posts() ) : $most_commented->the_post(); ?> , [/php]
You may find the ‘Most Commented’ list that is generated on your site turns up a lot of older posts. This can drive new traffic to older writing, but it isn’t ideal if you’d like to encourage visitors to comment on newer posts. Thankfully, we can tweak our query using Time Parameters.
First, add a function to your template that restricts the posts returned to a specific number of days. This code can be added to your
functions.php file if it’s going to be used in multiple points in your theme, or just in the template file it’s used in, as long as it’s added before the query. The example below is cutting off the number of posts at 30 days, but this number can be changed.
The above filter needs to be applied right before the most commented post query, like so:[php] add_filter( 'posts_where', 'filter_where' ); [/php]
The filter also needs to be removed after the Loop; otherwise, it will be applied to all following queries:[php] remove_filter( 'posts_where', 'filter_where' ); [/php]
The finished code should look something like this:[php] '" . date('Y-m-d', strtotime('-30 days')) . "'"; return $where; } add_filter( 'posts_where', 'filter_where' ); $most_commented = new WP_Query(array('orderby' => 'comment_count','order' => 'desc', 'posts_per_page' => '8')); if($most_commented->have_posts() ) : while( $most_commented->have_posts() ) : $most_commented->the_post(); ?> , [/php]
How do you encourage site visitors to comment on your posts? Share your ideas in this post’s comments!
Holy smokes — its been more than 6 months since WordPress Wednesdays debuted! Are you finding the posts helpful? Is there particular material you’d like to see covered? Please let me know in the comments, or drop me a line at firstname.lastname@example.org.