WordPress – Review your Post count with post meta
WordPress is a pretty amazing CMS package unlike blogger. Reason for that is, you don’t have to dig into codes much for modifications as there’ll be a plug-in for sure to fulfill your requirement. But overloading your custom wordpress site with plug-ins may also cause site loading issues, style issues.. etc.
Well, this time I wanted a simple script for me to check the post views in each posts just for my reference. Well, as usual I found some worpress plugins & at the same time a script which can do the job just using the post meta. I’m amazed that it worked like a charm. Nothing fancy in there, as I’m not a coder.. but, something which is useful for me though.
Always practice to back-up your files before modifying any scripts. Happy Coding!
Here’s how?
Add below code to your functions.php (on your current theme file) to display the number of views on each post.
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);
}
}
Once done, place below listed spinet “setPostViews” within the single.php inside the loop.
<?php
setPostViews(get_the_ID());
?>
Next is to place the blow snippet in wherever you would like to display the number of views. You should place it on both single.php and index.php
<?php
echo getPostViews(get_the_ID());
?>
This should be fine & if you finding issues after placing above scripts, please visit below source to find out more.
More : WPSnipp
