WordPress Shortcode: Popular Posts in Last X Number of Days
Shortcode Sunday! The time when we provide a semi-useful WordPress shortcode to kick your week off on a good note! This shortcode will allow you to display your most popular posts in the last 20 days or 30 days or 60 days or any number of days that you want to specify. The way that it determines what is “popular” is by the number of comments that the post has received. You will also be able to specify a limit to the number of popular posts you want to show.
So go ahead and add this function to wherever it is you are registering your shortcodes in WordPress…
function popularPostsShortcode($atts, $content = null) {
extract(shortcode_atts(array("limit" => '4', "days" => '60'), $atts));
global $wpdb;
$sql = $wpdb->prepare("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN DATE_SUB(NOW(), INTERVAL $days DAY) AND NOW() ORDER BY comment_count DESC LIMIT 0, $limit");
$posts = $wpdb->get_results($sql);
$list = '<div>';
foreach ($posts as $post) {
setup_postdata($post);
$id = $post->ID;
$title = $post->post_title;
$count = $post->comment_count;
if ($count != 0) {
$list .= '<a href="'.get_permalink($id).'" title="'.$title.'">'.$title.'</a> ('.$count.' comments)';
}
}
$list .= '</div>';
return $list;
}
Then all you have to do is register this shortcode after declaring the function…
add_shortcode('popularposts', 'popularPostsShortcode');
or if you are using it inside a class (as I highly recommend) you would register it in the following manner…
add_shortcode('popularposts', array($this, 'popularPostsShortcode'));
And if you want to use it in a page or post somewhere you’d just have to call it like so.
Limit refers to the maximum number of posts you want to show and days refers to the number of days prior to the current day that you want to get popular posts for. So this shortcode would get the top 5 most commented on posts in the last 60 days.
Enjoy






0 Responses to WordPress Shortcode: Popular Posts in Last X Number of Days