Category

How to track the most viewed post in WordPress using code?

1. Add the following piece of snippet in your function.php file, the code will help detect post views count and store it as a custom field for each post:

function set_post_views($postID) {
$count_key = ‘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);

2. Now to track no of times the post was viewed, lets place this snippet at the end of the function.php file:

function track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
set_post_views($post_id);
}
add_action( ‘wp_head’, ‘track_post_views’)

Now every time a visitor visit your post, the custom field will be updated.

3. To display the no of views for a post, add the following snippet of code in function.php file:

function get_post_views($postID){
$count_key = ‘post_views_count’;
$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 View”;
}
return $count.’ Views’;
}

Now where ever you want to display the post views for a specific post, just send the id as the parameter and it will fetch the no of views.

get_post_views(get_the_ID());