Limit terms included in a form taxonomy field or in a Views taxonomy filter

By default when you insert a taxonomy field in a form or add a filter control for a taxonomy to a View all terms are included, and there is currently no way to modify which terms appear.

You can use the following snippet to restrict the included terms for either a Form or a search View. You’ll need to specify the page(s) where the form or Views are added, the slug of the taxonomy, and the slug of the terms to whitelist or blacklist as required.

/**
 * Blacklist or whitelist terms in a taxonomy form field or View filter
 */
function tssupp_restrict_terms( $terms, $taxonomies, $args, $term_query ){

    // 1. pages where form (or search View) is inserted
    $pages = array( 118, 137 );

    // 2. which taxonomy (slug)
    $taxonomy = 'status';

    // 3. add terms to blacklist *OR* whitelist, not both
    $blacklist = array();
    $whitelist = array( 'archived', 'completed' );

    if ( is_page( $pages ) && $taxonomies[0] == $taxonomy ) {

        if ( !empty( $blacklist ) ) {

            foreach( $terms as $key => $term ){
     
                if ( in_array( $term->slug, $blacklist ) ) {
                    unset($terms[$key]);
                }
            }
        } elseif ( !empty( $whitelist ) ) {

            foreach( $terms as $key => $term ){
     
                if ( !in_array( $term->slug, $whitelist ) ) {
                    unset($terms[$key]);
                }
            }
        }
    }
     
    return $terms;
}
add_filter( 'get_terms', 'tssupp_restrict_terms', 10, 4 );

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments