wp_count_terms()WP 2.3.0

Counts how many elements (terms) are in the taxonomy, with or without posts.

1 time — 0.000664 sec (slow) | 50000 times — 26 sec (slow)

No Hooks.

Returns

String|WP_Error. How many terms are in the taxonomy. WP_Error if the taxonomy does not exist.

Usage

WP 5.6

wp_count_terms( $args );
$args(array/string)

Can accept all the same parameters as get_terms().

However, generally, it makes sense to specify only:

  • taxonomy(string)
    Name of the taxonomy.

  • hide_empty(true/false)
    true/1 - will count elements with posts.
    false/0 - will count all elements.

Default: array()

WP 5.5 and lower

wp_count_terms( $taxonomy, $args );
$taxonomy(string) (required)
Name of the taxonomy.
$args(array/string)

Can accept all the same parameters as get_terms(). However, generally, it makes sense to specify only one argument: hide_empty. Passing other parameters usually does not make sense. This parameter determines whether to count empty elements of the taxonomy:

  • hide_empty=1 - hide empty elements, which means elements with posts will be counted.
  • hide_empty=0 - do not hide elements, which means all elements will be counted.

Default: array()

Examples

14

#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
1

#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.

wp_count_terms() code WP 6.8.1

function wp_count_terms( $args = array(), $deprecated = '' ) {
	$use_legacy_args = false;

	// Check whether function is used with legacy signature: `$taxonomy` and `$args`.
	if ( $args
		&& ( is_string( $args ) && taxonomy_exists( $args )
			|| is_array( $args ) && wp_is_numeric_array( $args ) )
	) {
		$use_legacy_args = true;
	}

	$defaults = array( 'hide_empty' => false );

	if ( $use_legacy_args ) {
		$defaults['taxonomy'] = $args;
		$args                 = $deprecated;
	}

	$args = wp_parse_args( $args, $defaults );

	// Backward compatibility.
	if ( isset( $args['ignore_empty'] ) ) {
		$args['hide_empty'] = $args['ignore_empty'];
		unset( $args['ignore_empty'] );
	}

	$args['fields'] = 'count';

	return get_terms( $args );
}