0

Is there any way to display total views of all posts of one category? How to show that number on archive page? I have used this code to count views of each post:

function getPostViews($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');
        return"0 Views";
    }
    return $count.' Views';}function setPostViews($postID){
    $count_key ='post_views_count';
    $count = get_post_meta($postID, $count_key,true);
    if($count=='' || $count < 0){
        $count =0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key,'0');
    }else{
        $count = $count + 1;
        update_post_meta($postID, $count_key, $count);
    }
  }

But how to count total views for one category and display it? Please help me!

1
  • lol. you know this code sets the minumum number of views for any given post to 5 right off the bat. Are you interested in accuracy or inflated numbers?
    – Caspar
    Apr 14 '16 at 20:00
0
<?php
    $QUERY = new Wp_query(array( 
        'post_type' => 'post_type_here',
        'category_name' => 'category_name_here',
        // you can use cat id ...
    ));
    $counter = 0;
    while( $QUERY->have_posts() ) : $QUERY->the_post();
        $views = absint( getPostViews( $post->ID ) );
        $counter += $views;
    endwhile; wp_reset_postdata();
    echo $counter;

?>

getPostViews() and setPostViews :

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";
    }
    return $count;
}


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);
    }

}
1
  • 1
    Can you also explain as how the code works
    – bravokeyl
    Jul 4 '16 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.