Tracking Post Views Without Plugins for WordPress

Kevin Chard‘s nifty hack allows you to track post views without using any plugin in WordPress. Instead, it uses post meta, inserting a code in the functions.php, and a couple of other steps.

Insert this code inside your functions.php file:

?

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

 

Next step is to short code inside the single.php file within the loop, below “setPostViews”:

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

 

Finally, place this inside the template where you want to display the number of views:

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

 

You can find Kevin’s quick tutorial HERE.

Incoming search terms for the article:

Related Posts

We Love Icon Fonts

Adding Expires Headers In Ruby On Rails

Freewebsite.us, Your Affordable Website Creator

Validate Filename Before Uploading Image Using JavaScript

No comments