Skip to content

Instantly share code, notes, and snippets.

@munirkamal
Last active April 12, 2018 23:45
Show Gist options
  • Save munirkamal/8086198 to your computer and use it in GitHub Desktop.
Save munirkamal/8086198 to your computer and use it in GitHub Desktop.
Wordpress snippet to track and display post or page views in your wordpress website without using any plugin.
/*******************************************************/
/ Shared by www.codewordpress.com /
/ Add following code to Function.php file in your theme /
/*******************************************************/
<?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);
?>
/*********************************************************************/
// Put following code in your Single.php file within your post Loop
<?php
setPostViews(get_the_ID());
?>
// Put following code where you need to display the Views within single.php file.
<?php
echo getPostViews(get_the_ID());
?>
@quevenrib
Copy link

Hi! There is a way to include this information inside the loop?
I want to put the number of views in every post of the list. Inside page.php, not single.php.

Thank you!

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