WP Post Views Count without plugin

Today i am going to share how to add post views counting system on wordpress without any plugin.
First, copy this code of php function to yours THEME functions.php file. Basically /wp-content/themes/YOUR-THEME/functions.php

<?
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";
    }
    return $count;
}
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);
    }
}
?>

Here both functions accept a single parameter as mandatory, post id nnumber.
Now paste the following code on your post view page. Basically /wp-content/themes/YOUR-THEME/single.php file under wp post loop.

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

Post Views counting system is done. Now you need to print/show post views in site. Then paste the following code under wp loop on any page.

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

Thats all. You have Done.
If you are a developer then you can replace “get_the_ID()” with any post id to display any post views on anywhere or to increase post views.
Thanks for reading this.
If you face any problem regarding this, you can comment here.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *