Skip to main content

WordPress – How to Display Most Popular Posts by Views

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.
We’ll use the post Meta for storing the post views count. Using the stored Meta value, we’ll fetch the posts according to the views count. You need to modify only two files functions.php and single.php. After that, you can display the most popular posts using simple posts query.

functions.php File

Open the functions.php file of the activated theme and add the following code.
setPostViews() function add or update the post meta with post_views_count meta key.

/*
 * Set post views count using post meta
 */
function setPostViews($postID) {
    $countKey = 'post_views_count';
    $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);
    }
}

single.php File

Open the single.php file from activated theme directory and place the setPostViews() function inside the loop.

setPostViews(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();
?>

Comments

arfpsd said…
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.