Here we tell you way to track post views without a plugin using post meta.

Most of websites gives you different type of plugins to track post views. But use of so many plugins slow down your website speed. We will show you how to count post views and display it on your wordPress blog. You can easily track post views without using plugins. You will be able to see the post views count in the all post view page. you are actually be able to see how many visitors are actually reading your content. This post gives you code which you can easily embed in you function.php file and track post views using post meta. We are displaying the total Views code for every single post. The code counts views when you refresh or view the post.


You May Also Like:


To track Post views is a great way for web developer’s to check how many hits and views receive his post or articles. Use the following snippet to track post views on your wordpress blog. The first thing you want to do is add this snippet to the functions.php of your wordpress theme.After implementing this code no need to install any plugin.Sometimes plugin disturbs theme functionality so this problem is solved now.

Adding code to your functions.php file

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

// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

 

This code will set the post views. Just place this lines of code within the single.php inside the wordpress loop.

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

this code 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());
?>

About The Author

Related Posts

Leave a Reply

Your email address will not be published.