如何显示同一类别所有帖子的总浏览量?

时间:2016-04-14 作者:user3106691

有没有办法显示一个类别所有帖子的总视图?如何在存档页上显示该数字?我使用此代码统计每个帖子的浏览量:

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);
    }
  }
但是如何计算一个类别的总视图并显示它呢?请帮帮我!

1 个回复
SO网友:Soufiane L

<?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()和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);
    }

}

相关推荐

WP_DROPDOWN_CATEGORIES和自定义分类+自定义帖子类型

我已经创建了名为“的自定义帖子类型”;案例研究;(使用slug案例研究),支持自定义分类法,称为;主题;。我正在努力实现什么?简单的下拉列表,在选项选择上重定向到特定的分类术语页面。代码:<form id="category-select" class="category-select" action="<?php bloginfo(\'url\'); ?>" method="get&quo