Displays the most viewed posts at the sidebar are very helpful for visitors to find out the most popular post of your site. This tutorial will show you the simple way to display the most popular posts by views without using any plugin. You can get the most popular posts using simple WordPress most viewed posts query.

functions.php File

/*
 * Set post views count using post meta
 */
function setPostViews($postID) {
    $countKey = 'post_views_counts';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}
// function to display number of posts.
function getPostViews($postID){
    $count_key = 'post_views_counts';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0";
        // return "0 View";
    }
    return $count;
    // return $count.' Views';
}

single.php File

echo setPostViews(get_the_ID());
echo getPostViews(get_the_ID());

Display the Most Viewed Posts

The following query will fetch the posts based on the post_views_count meta key value. Place the following code in the sidebar or where you want to display the most popular posts list.

<?php
query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC');
if (have_posts()) : while (have_posts()) : the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile; endif;
wp_reset_query();
?>