Last active
June 19, 2019 06:31
-
-
Save jsakhil/951f1fd3b1f99aeb160a5cf1ea94fc5c to your computer and use it in GitHub Desktop.
WordPress Post Views Counter Without Any Plugin
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 | |
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); | |
?> |
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
// 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 | |
?> |
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 setPostViews(get_the_ID()); ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment