In this short tutorial we will learn how to count visitors on the the pages or posts and also how to display this information. For the code, you can use functions.php or you can use any code snippet plugin.
Code
We will get right to it, but first, let’s go over steps that we need in our code. we actually need three peaces of the code:
Main function:
- We must make sure that post_id exists. If we can’t get it, we exit.
- We must define a variable, that will hold the name of post metadata, where we will store post visit count number
- We try to get this data from post
- If this data is empty, we must create metadata and set it to 0
- If it’s not empty, then we can increase the counter
Below, you can find full function that do all of above. We will then call this function in the next section.
function mar_increase_post_view($postId = null){ //If our $postId is empty, we try to find it. if(!isset($postId) || empty($postId)){ global $post; $postId = $post->ID; } // define the name of metadata $countKey = "mar_count_key"; //we get the current view count $count = get_post_meta($postId, $countKey, true); //If there is no data yet if($count == ''){ $count = 0; //we set to be 0 as default value delete_post_meta($postId, $countKey); //just to be sure, we remove post meta if exists add_post_meta($postId, $countKey, $count); // //If there already is some number }else{ $count++; //increase count by 1 update_post_meta($postId, $countKey, $count); // updating post meta data } //Optionally, we can return the $count variable, if we will need it later on. return $count; }
Increasing the counter:
This one is simple, whenever you want to increase the counter, you call following function:
<?php mar_increase_post_view(get_the_ID()); ?>
What you want to do is, you want to call this function only once per page! This is very important. If you remember, on the last line of this function we returned $count
and if you put echo
before a call, it will write out the correct count. If you do this, then you don’t need next step.
Again, be careful to not call this function more than once a page!
Get post views (and showing it):
If you just want to show the page count, without increasing it, here is the solution. You will see that it is very similar to first function, but without logic of increasing.
function mar_get_post_views($postId = null){ //If our $postId is empty, we try to find it. if(!isset($postId) || empty($postId)){ global $post; $postId = $post->ID; } // define the name of metadata $countKey = "mar_count_key"; //we return the current view count return get_post_meta($postId, $countKey, true); }
You can put this code right next to the first one and it will be working just fine. Now we only need to call it anywhere that we would like to show page view count. In the example below, I created one div element where I call this function.
<div> Number of Views: <b><?php echo mar_get_post_views(get_the_ID()); ?></b> </div>
You see, it’s simple, right? 🙂