I’m using this code to show popular posts in wordpress, it is work good but i can not show the number of views , please help 🙂
function wpb_set_post_views($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
and this in the single page
wpb_set_post_views(get_the_ID());
and this to view post
<?php
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
the_title();
endwhile;
?>
To display the count of the page you should fetch the value using the meta key via
get_post_meta()
. Within the loop you can use theglobal $post
to get the current post ID.You can also simplify your function that records pageviews as well. Instead of deleting and then adding, you can just use the
update_post_meta()
function which will add the value if it doesn’t already exist, or update it if it does. By checking the result ofget_post_meta()
againstfalse
we can determine if the count needs to be initialized to 0. Once we have a value, update it to be the current value +1. Please note that on a high traffic site this isn’t guaranteed to be accurate due to race conditions updating the value for multiple requests at the same time.To count the post views, the first thing you have to do is to add the following code to your WordPress Theme functions.php
And now we will call this function in the single.php to update the count value in the Database.
Now in the same single.php file if we want to show the post view count, we can use this code:
Now to show all the popular post in the descending order by post view count. use this code:
Happy Coding