The get_terms WordPress PHP filter allows you to modify the terms found for a specific taxonomy before they’re returned.
Usage
add_filter( 'get_terms', 'your_custom_function', 10, 4 );
function your_custom_function( $terms, $taxonomies, $args, $term_query ) {
// your custom code here
return $terms;
}
Parameters
- $terms (array): Array of found terms.
- $taxonomies (array|null): An array of taxonomies if known.
- $args (array): An array of get_terms() arguments.
- $term_query (WP_Term_Query): The WP_Term_Query object.
More information
See WordPress Developer Resources: get_terms
Examples
Exclude a specific term from the list
Exclude a specific term by ID from the list of terms.
add_filter( 'get_terms', 'exclude_specific_term', 10, 4 );
function exclude_specific_term( $terms, $taxonomies, $args, $term_query ) {
$excluded_term_id = 12; // Set the term ID you want to exclude
if ( ! empty( $terms ) ) {
foreach ( $terms as $key => $term ) {
if ( $term->term_id == $excluded_term_id ) {
unset( $terms[ $key ] );
}
}
}
return $terms;
}
Modify the term name
Add a prefix to each term name.
add_filter( 'get_terms', 'prefix_term_names', 10, 4 );
function prefix_term_names( $terms, $taxonomies, $args, $term_query ) {
$prefix = 'Prefix: '; // Set the prefix you want to add
if ( ! empty( $terms ) ) {
foreach ( $terms as $key => $term ) {
$term->name = $prefix . $term->name;
}
}
return $terms;
}
Limit the number of terms returned
Limit the terms returned by the filter.
add_filter( 'get_terms', 'limit_terms_returned', 10, 4 );
function limit_terms_returned( $terms, $taxonomies, $args, $term_query ) {
$max_terms = 5; // Set the maximum number of terms you want to return
if ( count( $terms ) > $max_terms ) {
$terms = array_slice( $terms, 0, $max_terms );
}
return $terms;
}
Sort terms by custom order
Sort terms based on a custom order.
add_filter( 'get_terms', 'sort_terms_by_custom_order', 10, 4 );
function sort_terms_by_custom_order( $terms, $taxonomies, $args, $term_query ) {
if ( ! empty( $terms ) ) {
usort( $terms, function( $a, $b ) {
return strcmp( $a->slug, $b->slug ); // Replace 'slug' with the property you want to sort by
});
}
return $terms;
}
Filter terms based on their description
Show only terms with a specific word in their description.
add_filter( 'get_terms', 'filter_terms_by_description', 10, 4 );
function filter_terms_by_description( $terms, $taxonomies, $args, $term_query ) {
$specific_word = 'example'; // Set the specific word you want to filter by
if ( ! empty( $terms ) ) {
foreach ( $terms as $key => $term ) {
if ( strpos( strtolower( $term->description ), strtolower( $specific_word ) ) === false ) {
unset( $terms[ $key ] );
}
}
}
return $terms;
}