wp_count_terms()
Count how many terms are in Taxonomy.
Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
Uses: get_terms()
1 time — 0.000664 sec (slow) | 50000 times — 26 sec (slow)
No Hooks.
Return
String|WP_Error
. Numeric string containing the number of terms in that taxonomy or WP_Error if the taxonomy does not exist.
Usage
wp_count_terms( $args, $deprecated );
- $args(array|string)
- Array or string of arguments. See WP_Term_Query::__construct() for information on accepted arguments.
Default: empty array - $deprecated(array|string)
- Argument array, when using the legacy function parameter format. If present, this parameter will be interpreted as $args, and the first function parameter will be parsed as a taxonomy or array of taxonomies.
Default: ''
Examples
#1 Count the elements of the taxonomy taxa
For WP 5.6+:
echo wp_count_terms( [ 'taxonomy' => 'taxa', 'hide_empty' => false ] ); // Get something like: // 100
#2 Count the elements of the taxonomy taxa
Demonstration of how the function works. Suppose we have a taxonomy taxa
and it has 50 items with posts and 50 empty items.
// all elements with empty echo wp_count_terms( 'taxa', 'hide_empty=0' ); // > 100 // only items with posts echo wp_count_terms( 'taxa', 'hide_empty=1' ); // > 50 // can be written as an array echo wp_count_terms( 'taxa', [ 'hide_empty'=>1 ] ); // > 50 // make sure there is a dachshund $count = wp_count_terms( 'taxa', [ 'hide_empty'=>1 ] ); if( ! is_wp_error( $count ) ){ echo $count; // > 50 }
Changelog
Since 2.3.0 | Introduced. |
Since 5.6.0 | Changed the function signature so that the $args array can be provided as the first parameter. |