taxonomy list display custom post count

I use $term->count to display post count but it displays the total count of all type of custom posts attached to taxonomy…

I just want to display the count of only a specific custom post type attached to taxonomy

$icon = get_field('logo', $term->taxonomy . '_' . $term->term_id); 
                        $va_category_HTML .= '<li class="logolar" '.$carrentActiveClass.'>' .'<a class="rownum">' .$i++. '</a>'. '</a>';
                        $va_category_HTML .= sprintf('<img src="https://wordpress.stackexchange.com/questions/340250/%s" />', $icon) . '</a>';
                        $va_category_HTML .='<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
                        if (empty( $instance['wcw_hide_count'] )) {
                        $va_category_HTML .='<span class="post-count">'.$term->count.'</span>';
                        }

                        $va_category_HTML .='</li>';

1 Answer
1

What makes this annoying is that the count is a wp_term_taxonomy table.

So the way to do this is a custom query:

function wpse340250_term_count( WP_Term $term, $post_type) {
    $q_args = [
        'post_type' => $post_type,
        'nopaging' => true, // no limit, pagination
        'fields' => 'ids', // only return post id's instead of full WP_Post objects will speed up
        'tax_query' => array(
            array(
                'taxonomy' => $term->taxonomy,
                'field'    => 'term_id',
                'terms'    => $term->term_id,
            ),
        ),
    ];
    $term_count = get_posts($q_args);

    return count($term_count);
}

So change the line to:

$va_category_HTML .='<span class="post-count">'.wpse340250_term_count($term, 'CUSTOM_POST_TYPE').'</span>';

Just set the correct posttype.

Leave a Comment