2

I want to show on a list of taxonomy with corresponding posts counts of published items only. Checking the WP documentation, It seems I can ALMOST achieve that by using the get_terms function https://developer.wordpress.org/reference/functions/get_terms/ but I get ALL the posts counts including draft and trashed.

$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/>';
}

Does WP have a built in args to display it from the get_terms function because I don't see it under the documentation? Is there any other functions or filter that I can try to achieve my desired output?

1
  • 2
    The count property on terms is only published posts. You can see in the source for _update_post_term_count(). Oct 26, 2017 at 7:26

1 Answer 1

3

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/>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.