Show the number of total views for all posts inside a WordPress category

To display the number of total views for all posts inside a WordPress category the simplest solution is to count the page views of each post, and then call the post views on the category page.

Open the functions.php file of the current template and add the following code:

function fa_get_tax_views($term_id = null) {
    if (!$term_id) {
        $term = get_queried_object();
        $term_id = $term->term_id;
    }
    if (!$term_id) return;
    $view = get_term_meta($term_id , '_views' , true) ? get_term_meta($term_id , '_views' , true) : 0;
    return $view;
}

function fa_set_tax_views() {
    if (!is_category() && !is_tag()) return;
    $term = get_queried_object();
    $term_id = $term->term_id;
    $view = fa_get_tax_views($term_id);
    update_term_meta($term_id, '_views' , $view + 1);
}

add_action('get_header', 'fa_set_tax_views');</code class="">

And to display the number of total category views add:

<?php echo fa_get_tax_views();?>

Source: WordPress主题开发:统计显示WordPress分类目录浏览量

Was this post helpful?

Leave a Reply