Show Page Views in WordPress

This post will show you how to display the number of times a particular page or post has been viewed in WordPress. Many sites do this to show the popularity and traffic of a particular entry. Do do this, add the following function somewhere in your functions.php file in your WordPress theme…

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

Then to use this function all you have to do is call it when looping through posts (such as you do in index.php) or pages.

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

0 Responses to “Show Page Views in WordPress”

Leave a Reply