Is there anyway to show in a template for a post, how many times that post has been viewed, like hits without some sort of plugin? It seems wordpress would have this built in, but I am unable to find any template tags for such a think in the documentation?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Not in core. You can use post meta to store this information on page loads. If you have caching plugins enabled, you might want to increment the hit counter with an AJAX call, otherwise you can just add this directly in your single.php and page.php templates:
//Add to functions.php
function get_hits(){
global $post;
$hits = get_post_meta($post->ID, '_hit-counter', true);
return $hits;
}
function update_hits($count){
global $post;
$count = $count ? $count : 0;
$hits = update_post_meta($post->ID, '_hit-counter', $count++);
return $hits;
}
//Usage within the loop
update_hits(get_hits());
Method 2
No, WP doesn’t have such functionality built-in. Probably because updating the post table on each page hit would slow down the site.
You’ll have to use wp-postviews or something related.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0