Skip to content

Instantly share code, notes, and snippets.

@jsakhil
Last active June 19, 2019 06:31
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 jsakhil/951f1fd3b1f99aeb160a5cf1ea94fc5c to your computer and use it in GitHub Desktop.
Save jsakhil/951f1fd3b1f99aeb160a5cf1ea94fc5c to your computer and use it in GitHub Desktop.
WordPress Post Views Counter Without Any Plugin
<?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 issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
?>
// Use the following line of code where you want to display the view number inside the loop.
// It will get the post view number from the last step where you call the set function to track the post views.
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
echo getPostViews(get_the_ID());
//
} // end while
} // end if
?>
<?php setPostViews(get_the_ID()); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment