Status
Not open for further replies.

ven666detta

Active Member
430
2011
49
0
I have a wordpress.org site and I was wondering what plugin any of you guys are using for your site that counts unique post views and page views...
 
5 comments
I have a wordpress.org site and I was wondering what plugin any of you guys are using for your site that counts unique post views and page views...

What do think the plugin repository is there for, try to search and pick the popular one with good rating. i have used a snippet before without installing a plugin, google it.
 
Open Your functions.php

Add this code:

PHP:
/* Add Post Views  ------------------------------------*/
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);
    }
}

Open Single.php of your theme add this anywhere:
PHP:
<?php setPostViews(get_the_ID()); ?>

And final to display the post views count(number)
Use this code (Index.php or any template..)
PHP:
<?php echo getPostViews(get_the_ID()); ?>

This is what I use and works perfect
 
Last edited:
Open Your functions.php

Add this code:

PHP:
/* Add Post Views  ------------------------------------*/
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);
    }
}

Open Single.php of your theme add this anywhere:
PHP:
<?php setPostViews(get_the_ID()); ?>

And final to display the post views count(number)
Use this code (Index.php or any template..)
PHP:
<?php echo getPostViews(get_the_ID()); ?>

This is what I use and works perfect

I have suggested this code before. While there is a simple code, why will we use a plugin? :D
 
Status
Not open for further replies.
Back
Top