Created
February 28, 2012 23:58
-
-
Save ninnypants/1936312 to your computer and use it in GitHub Desktop.
Custom Field Post View Counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn't $count start at 1? Since the first time it is called it will be the post being viewed once.