How-Tos
Posted By Azker

Track post views in wordpress with post meta [no plugins required]


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.

[box type=”note”]Always practice to back-up your files before modifying any scripts. Happy Coding![/box]

Okay, enough said & here’s how?

Add below code to your [highlight]functions.php[/highlight] (on your current theme file) to display the number of views on each post.

[box]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);
}
}[/box]

Once done, place below listed spinet [highlight]”setPostViews”[/highlight] within the [highlight]single.php[/highlight] inside the loop.

[box]<?php

setPostViews(get_the_ID());
?>[/box]

Next is to place the blow snippet in wherever you would like to display the number of views. You should place it on both [highlight]single.php[/highlight] and [highlight]index.php[/highlight]

[box]<?php

echo getPostViews(get_the_ID());
?>[/box]

This should be fine & if you finding issues after placing above scripts, please visit below source to find out more.

[box type=”download”]More: WPSnipp[/box]


A lonely being living far away from the pearl of Indian ocean. Happens to be a Telecom nomad moved towards networking who's now into hospitality IT with Resort developing exposure. An open-source fanatic, a geek and indeed a minion fan. I prefer football & popcorn ^_^ I co-founded Aqurex Technologies (https://aqurex.com), allowing users to benefit expensive solutions for an affordable value.

View Comments
View Comments
There are currently no comments.