Friday 23 October 2020

WordPress Post Views Count Without Plugin

 Step1"
Add this code in current WordPress active theme in function.php file

<?php

function get_PostViews($postID){
    $count_key = 'post_views_count';
    $post_count = get_post_meta($postID, $count_key, true);
    if($post_count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $post_count.' Views';
}

function set_PostViews($postID) {
    $count_key = 'post_views_count';
    $post_count = get_post_meta($postID, $count_key, true);
    if($post_count==''){
        $post_count = 0;
       delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $post_count++;
        update_post_meta($postID, $count_key, $post_count);
    }
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
?>

 Step2:
Now add this function code in active themes in single.php file within the loop. It will manage the views and set the post views of each post.

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

 Step3:
Add this code line in inside the post loop where you want to display post count.

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