How to Track post views without a plugin?

All QuestionsCategory: WordPressHow to Track post views without a plugin?
S M Hasibul Islam Staff asked 3 years ago

I would like be post view count appear just above the post, but I don’t really know the code I have to paste. Here is my code

function getPostViews($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";

}

return $count.' ';

}

Have any body for help me?

1 Answers
S M Hasibul Islam Staff answered 3 years ago

Hello, I have use this code & it’s working on my site. Given bellow my code

function getPostViews($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";

}

return $count.' ';

}

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

}

}