List taxonomy / category count showing list published posts only

Checked the source, and it seems the only way to get this done is filtering the output count for each term, you can achieve that by inserting this filter before your get_terms call. Note that this will now always display published item count so be careful on its usage.

function get_terms_filter_published( $terms, $taxonomies, $args ) {
  global $wpdb;
  $taxonomy = $taxonomies[0];
  if ( ! is_array($terms) && count($terms) < 1 ) {
    return $terms;
  }

  $filtered_terms = array();
  $ctr = 0;
  foreach ( $terms as $term ) {
    $result = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts p JOIN $wpdb->term_relationships rl ON p.ID = rl.object_id WHERE rl.term_taxonomy_id = $term->term_id AND p.post_status="publish" LIMIT 1");
    $published_terms[ $ctr ] = $term;
    if ( intval($result) > 0 ) {
        $published_terms[ $ctr ] = $term;
    } else {
        // you can comment this out if you don't want to show empty terms
        $published_terms[ $ctr ]->count = 0;
    }
    $ctr++;
  }
  return $published_terms;
}

add_filter('get_terms', 'get_terms_filter_published', 10, 3);

$taxonomy = 'item_category';
$args =  array(
  'hide_empty' => false,
  'orderby'    => 'name',
  'order'      => 'ASC'
);
$terms = get_terms( $taxonomy , $args );

foreach( $terms as $term ) {
  echo $term->name . ' - ' . $term->count . '<br/>';
}

Leave a Comment