Show Post Views Count on Posts Without Any Plugin in WordPress

Advertisement

Some premium themes comes with post view count features. We can use same features on our WordPress blog also but it needs plugins for show. But you not like plugin like me then you can try my 2nd alternative method for show post view count on website. It is php code method you need edit your theme php files. You can see that every theme show author name on post so we can show post view count also there so that we avoid additional CSS coding for post views count in well manner.

First open you functions.php and enter this code with in php tag.

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

Now open your single.php file and enter this code

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

see pic below I insert this code in my file. In this pic you can see that I insert code after while(have_posts().

show-post-view-count-in-wordpress-theme-1

This code only for initialize function in single.php file now you need to show post view count. For show post view counts use below code.

<?php echo getPostViews(get_the_ID()); ?>
I use this code near author show code and now my code is same like this:

<div class=”postdate”><span class=”sadmin”><?php _e(‘Posted by’,THEME_LANG_DOMAIN); ?> <?php the_author(); ?> <?php _e(‘on’, THEME_LANG_DOMAIN); ?> <?php the_time(‘F jS Y’) ?> <?php _e(‘in’,THEME_LANG_DOMAIN); ?> <?php the_category(‘, ‘) ?>&nbsp;&nbsp;&nbsp;<?php edit_post_link(__(‘edit’,THEME_LANG_DOMAIN)); ?>&nbsp;&nbsp;&nbsp;<?php comments_popup_link(__(‘No Comment’,THEME_LANG_DOMAIN), __(’1 Comment’,THEME_LANG_DOMAIN), __(‘% Comments’,THEME_LANG_DOMAIN)); ?>&nbsp;&nbsp;&nbsp;<?php echo getPostViews(get_the_ID()); ?></span>

</div>

After apply this code on my theme result is:

show-post-view-count-in-wordpress-theme-2

I put <?php echo getPostViews(get_the_ID()); ?>  this code after comment show code. You can use this code on your home page also for show post views of every post. If you feel any problem for implement this code on your theme then please comment below.

Advertisement

Comments

  1. By Danny

  2. By युगल मेहरा

  3. By sunny

    • By admin

  4. By hatatitla

  5. By rahman

  6. By mosak

  7. By Desene

  8. By Dinesh Babu