Shortcode: Display Most Popular or Commented Posts

Putting some of your older posts in sidebar or on a homepage is a good approach not only for SEO of your blog but also offer interested content to your visitor. You may have hundreds of posts on your blog, you should be showing the ones that has been most popular among the visitors. This shortcode will let you list most commented posts (or any custom post type) from a single category or multiple categories.

If you prefer a widget you may check out our All in one Post Listing Widget.

Usage

[popular_posts]
[popular_posts cat="news" posts_per_page="8"]
[popular_posts cat="wordpress" post_type="event" post_status="upcoming"]

Snippet

add_shortcode("popular_posts", "wpds_popular_posts");
function wpds_popular_posts($atts) {
    $args = shortcode_atts(array(
        'cat' => '',                // Comma separated category IDs or slugs
        'post_type' => 'post',      // Type of Post
        'post_status' => 'publish', // Include any post status
        'posts_per_page' => 5       // Number of popular posts to show
    ), $atts);

    $args['orderby'] = 'comment_count';
    $args['order'] = 'DESC';

    $popular_posts = new WP_Query($args);
    if( $popular_posts->have_posts() ) {
        echo '<ul class="wpds_popular_posts">';
        while ($popular_posts->have_posts()) {
            $popular_posts->the_post();
            echo '<li><a href="'.get_permalink().'" rel="bookmark" title="'.the_title_attribute('echo=0').'">';
            echo get_the_title().'</a></li>';
        }
        echo '</ul>';
     }

    wp_reset_query();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>