Why does my custom taxonomy show a total count across all post types

There is currently a trac ticket on the fact that taxonomy counts are global (include all post types). Related trac ticket.

To fix this you can remove the column and add your own using the manage_edit-{$taxonomy}_columns filter:

add_filter('manage_edit-season_columns','my_season_columns');
function my_season_columns($columns){
    unset($columns['posts']);
    $columns['cpt_count'] = 'Races';

    return $columns;
}

You then tell WordPress what to fill this column with using the manage_{$taxonomy}_custom_column filter. For this you check we are in the ‘cpt_count’ column and return what ever the count is. You’ll need a custom function to do this.

add_filter('manage_season_custom_column','my_season_alter_count',10,3);
function my_season_alter_count($value, $column_name, $id ){
    if( 'cpt_count' == $column_name )
        return wpse50755_get_term_post_count_by_type($id,'season','race');

    return $value;
}

Lastly, define the custom function wpse50755_get_term_post_count_by_type. This was taken from this answer.

function wpse50755_get_term_post_count_by_type($term,$taxonomy,$type){

  $args = array( 
    'fields' =>'ids',
    'numberposts' => -1,
    'post_type' => $type, 
     'tax_query' => array(
        array(
            'taxonomy' => 'event-category',
            'field' => 'id',
            'terms' => intval($term)
        )
      )
   );
   $ps = get_posts( $args );

   if (count($ps) > 0){
       return count($ps);
   }else{
       return 0;
   }
 }

This is untested, but conceptually it should work.

You’ll need to do a bit more work to make the column sortable, since you’ll need to work out how to tell WordPress to sort the terms in count (post type specific) order.

Leave a Comment