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="%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>';

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(
                '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.

  • i am so grateful to you. thank you so much.. just one more question.. order by still run according to total post count Jun 14 '19 at 11:30
  • $terms = get_terms( $instance['wcw_taxonomy_type'], array('orderby' => 'count', 'order' => 'DESC','hide_empty'=>0 )); Jun 14 '19 at 11:32
  • That is a separate question, if this answers the main question accept is as such. And open a new question. Maybe someone else knows this without researching it.
    – janw
    Jun 14 '19 at 12:14
  • ok i will open new question.. thank you very much you made unbelivable happy.. god save you Jun 14 '19 at 12:16
  • If this answer helped this question please mark is as answered, left to a answer is a green checkmark.
    – janw
    Jun 14 '19 at 12:54

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.