WordPress - Track Post Views Using Custom Code Step

Track Post Views

Wordpress is more popular with making Blog website. And here it comes with enhanced feature of "Post Views" feature you can use to track views per post.

Blog

Follow below steps for quicker idea:

Step 1: This part of the tracking views snippet will set the post views. Just place this snippet below within the single.php inside the wordpress loop.

<?php
       setPostViews(get_the_ID());
?>

Step 2: The snippet below is optional, so use this if you would like to display the number of views within your posts. Place this snippet within the loop.

<?php 
       echo getPostViews(get_the_ID()); 
?>

Step 3: Finally, add this snippet below to the functions.php of your wordpress theme to track and display the number of views for each post.

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);
    }
}

Hope you enjoyed the new feature which may help you and make your website richer and user-friendly. 

Leave your useful feedbacks guys and need any assistance regarding Web Development Services Contact us now!