Hi, I’m developing a theme and I needed to create a meta field to count the hits for each post.
Follows the 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 View";
}
return $count.' Views';
}
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);
}
}
Well, to test it I created 3 posts and when I hit the post #1, the counter of the post #1 and post #2 are increased simultaneously. The same issue occurs when I hit any post: the next post counter is increased too. Only the last post (most recent) works fine.
The functions are called in the single.php file using the get_the_ID() function as the parameter.