How to Remove Specific Categories from a List of Terms

Updated on:

When working with WordPress or any other content management system, there are often cases where you need to manipulate the list of terms associated with a post. One common task is to remove certain categories from the list of terms.

GenerateTips

Use WP filter get_the_terms()

We can use the WP filter get_the_terms() to exclude specific categories from the list of terms:

add_filter('get_the_terms', 'hide_categories_terms', 10, 3);
function hide_categories_terms($terms, $post_id, $taxonomy){
    $exclude = array(2, 3, 4);

    if (!is_admin()) {
        foreach($terms as $key => $term){
            if(in_array($term->term_id, $exclude)) unset($terms[$key]);
        }
    }
    return $terms;
}

In the above code, we excluded categories with IDs: 2, 3, 4. You just need to replace the IDs with the actual category IDs that you want to exclude.

NOTE: the PHP snippet can be added to a child theme’s functions.php or via a plugin like Code Snippet.