Skip to content

Instantly share code, notes, and snippets.

@ninnypants
Created February 28, 2012 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ninnypants/1936312 to your computer and use it in GitHub Desktop.
Save ninnypants/1936312 to your computer and use it in GitHub Desktop.
Custom Field Post View Counter
<?php
/*
For a simple way to keep track of the number of post views, paste this snippet into the functions.php, and then follow steps 1 and 2.
*/
function getPostViews($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');
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);
}
}
/*
Step 1: Paste the code below within the single.php within the loop:
setPostViews(get_the_ID());
Step 2: Paste the snippet below anywhere within the template where you would like to display the number of views:
echo getPostViews(get_the_ID());
*/
@ninnypants
Copy link
Author

Shouldn't $count start at 1? Since the first time it is called it will be the post being viewed once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment