Skip to content

Instantly share code, notes, and snippets.

@antoniofrignani
Created June 4, 2012 09:54
Show Gist options
  • Save antoniofrignani/2867546 to your computer and use it in GitHub Desktop.
Save antoniofrignani/2867546 to your computer and use it in GitHub Desktop.
[WP] - Track post views without a plugin using post meta
// http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta/
// functions.php
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);
}
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
// Step 1: Place this snippet bellow "setPostViews" within the single.php inside the loop.
<?php
setPostViews(get_the_ID());
?>
// Step 2: Place this snippet bellow within the template where you would like to display the number of views.
<?php
echo getPostViews(get_the_ID());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment