← Writing

April 7, 2016

WP Post Views Count without plugin

WP Post Views Count without plugin

Today I am going to share how to add a post views counting system on WordPress without any plugin.

First, copy this PHP function code to your theme’s functions.php file — typically at /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);
    }
}
?>

Both functions accept a single mandatory parameter — the post ID.

Now paste the following code in your post view page, typically /wp-content/themes/YOUR-THEME/single.php under the WP post loop:

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

The post views counting system is now set up. To display the view count, paste the following code under the WP loop on any page:

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

That’s all. Done!

If you are a developer, you can replace get_the_ID() with any post ID to display or increment views for any post anywhere.

Thanks for reading. If you face any problem, feel free to comment.

  • post views count
  • without plugin
  • Wordpress
  • wp extend
  • wp function
  • wp plugin