Last active
April 12, 2018 23:45
-
-
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.
This file contains hidden or 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
/*******************************************************/ | |
/ 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()); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!