I'm trying to show the post views for every post on a blog page (so in a loop).
I tried it with the following code in the functions.php:
// function to count views.
function setAndViewPostViews($postID) {
$count_key = 'views';
$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);
}
return $count; /* so you can show it */
}
Then in the loop function I used this code:
<?php echo setAndViewPostViews(get_the_ID()); ?>
However, every post gets a count added every time the blog page is reloaded, strange thing is that the id is different for every post. How can I make this it will only count the every posts? And, if possible, how would I make it so that it only counts every individual views?
Thanks in advance!
Btw. I know there are a lot of plugins that do this, it's not my intention to use one, so please don't suggest a plugin.
is_single()
oris_singular()
to restrict the counter updates?<?php echo setAndViewPostViews(get_the_ID()); ?>
under this while loop:<?php while ($query->have_posts()) : $query->the_post(); session_start();