Jump to content


* * * * * 1 votes

Track post views in WordPress Manually

wordpress

  • Please log in to reply
No replies to this topic

#1 webrobot

webrobot

    Member

  • Members
  • PipPip
  • 20 posts

Posted 07 January 2012 - 04:35 PM

Add this snippet into the functions.php of your wordpress theme then follow step 1. and step 2. to display the number of views for 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);
	}
}


Step 1.

Place this snippet bellow “setPostViews” within the single.php inside the loop.
<?php
		  setPostViews(get_the_ID());
?>


Step 2.

Place this snippet bellow within the template where you would like to display the number of views.
<?php
		  echo getPostViews(get_the_ID());
?>






Also tagged with one or more of these keywords: wordpress