In this post we’ll see how to add post views in WordPress without a plugin, and make them visible to everyone (or just to administrators, if you want to keep a little secret about how your business is going). We will mainly work on the functions.php
file of our theme, with two brand new functions that allow us to store and show post views wherever we want.
Let’s do this.
How to add post views in a WordPress site
So, the first thing we have to do is to create a new function in functions.php
. It will create a custom meta field in our posts, or just update it if it already exists.
function count_post_views( $post_id ){ $views_key = 'post_views'; $count_views = ( int ) get_post_meta( $post_id, $views_key, true ); if( $count_views < 1 ){ delete_post_meta( $post_id, $views_key ); $count_views++; add_post_meta( $post_id, $views_key, $count_views ); } else { $count_views++; update_post_meta( $post_id, $views_key, ( string ) $count_views ); } }
Here we first count the views value that already exists, if it exists; if it’s zero, or not existing, we delete the meta field and add it again with the value of 1. Else, if the value already exists and is greater that 1, we just add 1 to it and update the value.
Now, of course, we have to tell WordPress when to execute this function, and we can do that just by calling it inside our single.php
(or page.php
, or whatever custom post type we want). So, let’s go for example inside our single.php
, find the loop, and call the function from inside it, by passing our post ID as a parameter.
if( have_posts() ){ while( have_posts() ){ // We have to find the while loop and put our function in it the_post(); count_post_views( get_the_ID() ); } }
Okay, so now, every time someone reads a post, our value will update by 1, and that’s exactly what we wanted. Great.
Now, of course, we want to show our post views in our frontend.
How to show post views in a WordPress site
Now: we have our value stored, but we have to show it. So let’s go back to our functions.php
and create another function, that will check for our value and return it (or put it to 0 if it doesn’t exist).
function store_post_views( $post_id ){ $views_key = 'post_views'; $count_views = get_post_meta( $post_id, $views_key, true ); if( $count_views == '' ){ delete_post_meta( $post_id, $views_key ); add_post_meta( $post_id, $views_key, '0' ); return 0; } return $count_views; }
Great. Now the last step: go back to our single.php
, or whatever content we want, and actually show our views count. We’ll do it by calling our function wherever we want our data to appear.
To everyone first:
$views_count = store_post_views( get_the_ID() ); echo esc_html( $views_count );
…or just to administrators:
if( current_user_can( 'administrator' ) ){ $views_count = store_post_views( get_the_ID() ); echo esc_html( $views_count ); }
This is a great way to track our content views without using plugins or external tools.
(image courtesy of Yinjaa-Barni Art)