The get_the_terms WordPress PHP filter allows you to modify the list of terms attached to a given post.
Usage
add_filter('get_the_terms', 'your_custom_function', 10, 3); function your_custom_function($terms, $post_id, $taxonomy) { // your custom code here return $terms; }
Parameters
- $terms: WP_Term[]|WP_Error – Array of attached terms, or WP_Error on failure.
- $post_id: int – Post ID.
- $taxonomy: string – Name of the taxonomy.
More information
See WordPress Developer Resources: get_the_terms
Examples
Hide specific category from terms
This example hides a specific category with the ID 5 from the list of terms.
add_filter('get_the_terms', 'hide_specific_category', 10, 3); function hide_specific_category($terms, $post_id, $taxonomy) { if ($taxonomy === 'category') { $terms = array_filter($terms, function ($term) { return $term->term_id != 5; }); } return $terms; }
Add a custom term to the terms list
This example adds a custom term object to the terms list.
add_filter('get_the_terms', 'add_custom_term', 10, 3); function add_custom_term($terms, $post_id, $taxonomy) { if ($taxonomy === 'post_tag') { $custom_term = (object) [ 'term_id' => 999, 'name' => 'Custom Tag', 'slug' => 'custom-tag', 'taxonomy' => 'post_tag' ]; $terms[] = $custom_term; } return $terms; }
Change the order of terms
This example sorts the terms alphabetically by their name.
add_filter('get_the_terms', 'sort_terms_alphabetically', 10, 3); function sort_terms_alphabetically($terms, $post_id, $taxonomy) { usort($terms, function ($a, $b) { return strcmp($a->name, $b->name); }); return $terms; }
Exclude terms with a specific parent
This example excludes terms that have a specific parent term ID, for example, 10.
add_filter('get_the_terms', 'exclude_terms_with_specific_parent', 10, 3); function exclude_terms_with_specific_parent($terms, $post_id, $taxonomy) { $terms = array_filter($terms, function ($term) { return $term->parent != 10; }); return $terms; }
Modify term names
This example appends a custom text to the term names.
add_filter('get_the_terms', 'modify_term_names', 10, 3); function modify_term_names($terms, $post_id, $taxonomy) { foreach ($terms as $term) { $term->name = $term->name . ' - Custom Text'; } return $terms; }