Reputation: 65
I am trying to display post type views without plugin.
For example (33 views)
My post type is portfolio. Any idea how to display these views with each post?
Upvotes: 2
Views: 2090
Reputation: 9941
I use the following to display post views.
function setPostViews($postID) {
$user_ip = $_SERVER['REMOTE_ADDR']; //retrieve the current IP address of the visitor
$key = $user_ip . 'x' . $postID; //combine post ID & IP to form unique key
$value = array($user_ip, $postID); // store post ID & IP as separate values (see note)
$visited = get_transient($key); //get transient and store in variable
//check to see if the Post ID/IP ($key) address is currently stored as a transient
if ( false === ( $visited ) ) {
//store the unique key, Post ID & IP address for 12 hours if it does not exist
set_transient( $key, $value, 60*60*12 );
// now run post views function
$count_key = 'views';
$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);
}
}
}
This function checks the IP and stores it. The transient is set to 12 hours, so if an user visits the page again within 12 hours, it won't count as another view. You need to add the following code <?php setPostViews(get_the_ID()); ?>
in your single.php
anywhere inside the loop.
The following function will display the post views. You can customize this to change the output text
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';
}
Just add <?php echo getPostViews(get_the_ID()); ?>
where you need to display the post views
Upvotes: 2