Get Popular Posts by Views in WordPress

In the past we have shown you how to get popular post in WordPress. In this article, we will show you how to track and display popular posts by views in WordPress without using any plugins.

First thing we need to do is create a function that will detect post views count and store it as a custom field for each post. To do this, paste the following codes in your theme’s functions.php file

//This function will count post views. there is one parameter postID
function SetPostViews($postID) {
    $meta_key = 'post_views_count';
    $count = get_post_meta($postID, $meta_key, true);
    if($count==''):
        $count = 0;
        delete_post_meta($postID, $meta_key);
        add_post_meta($postID, $meta_key, '0');
    else:
        $count++;
        update_post_meta($postID, $meta_key, $count);
    endif;
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now that you have a function in your function file, now we need to call this function on post details pages.To do this, you would need to paste the following code inside your post details loop:

SetPostViews(get_the_ID());

Once you have placed this, every time a user visits the post, the custom field will be updated.

Now we need to show top 5 viewed post. To do this, you would need to paste the following code inside your function file

//This function will show top viewed post. there is one parameter "QTY" length of showed post.
function GetPopularPost($QTY){
$popularpost = new WP_Query( array( 'posts_per_page' => $QTY, 'meta_key' => 'post_views_count', 'orderby' => 'post_views_count', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
echo get_the_title();
endwhile;
}

At this time you have a function for show popular posts. just call this function where you want to show popular posts.

GetPopularPost("5");