Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show view count of a post on wordpress

I'm working on a wordpress, and using a plugin wordpress popular posts, and facing this issue.

How can I show a count of how many times a page has been viewed by visitors on category listing page or index page of the blog. This information is already there which is being used by plugin to display same in sidebar, not sure how can I use the same plugin data to show page view count on blog page.

I tried to find this, but didn't get exactly what I want.

Pls advise how to do this?

Plugin I use is http://wordpress.org/extend/plugins/wordpress-popular-posts/

like image 309
Krunal Avatar asked Sep 18 '25 00:09

Krunal


2 Answers

You can simply do it without a plugin.

To count the post views, the first thing you have to do is to add the following code to your WordPress Theme functions.php

<?php
/*
 * Set post views count using post meta//functions.php
 */
function customSetPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '1');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}
?>

And now we will call this function in the single.php to update the count value in the Database.

<?php 
    customSetPostViews(get_the_ID());//single.php
?>

Now in the same single.php file if we want to show the post view count, we can use this code:

<?php
    $post_views_count = get_post_meta( get_the_ID(), 'post_views_count', true );
    // Check if the custom field has a value.
    if ( ! empty( $post_views_count ) ) {
        echo $post_views_count;
    }
?>

Now to show all the popular post in the descending order by post view count. use this code:

<?php//popular post query
    query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
    order=DESC');
    if (have_posts()) : while (have_posts()) : the_post();
?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
    endwhile; endif;
    wp_reset_query();
?>

Happy Coding

like image 172
Sujeet Kumar Avatar answered Sep 19 '25 16:09

Sujeet Kumar


There is a function called wpp_get_views provided by the plugin. If you know the ID of the post/page for which you want to show the view count, all you need to do is to call the function with that ID as the parameter. For example:

$count = wpp_get_views($post->ID); 
like image 45
onokazu Avatar answered Sep 19 '25 18:09

onokazu