Hook

Exclude specific Taxonomy Terms from a View Query

Sometimes, we want to have a View Custom Front End Search filtering our Loops by Taxonomy terms, but we may want to exclude a few of those Terms both from the results, and the Custom Search. Natively this is possible in Toolset by using a Query Filter – but this Query Filter will be overwritten by any Custom Search we setup.

Hence, we need a Custom PHP Code (a filter) to adjust our Loop results and the Views Query.

In this example we assume we have a View listing posts with a Custom Search for the Post Tags, and we want to exclude the specific Post Tag with ID 37 from the Search and the Loop results. We use the Toolset Views wpv_query_filter hook to add our logic.

add_filter( 'wpv_filter_query', 'tkt_remove_dev_tags', 101, 3 );

function tkt_remove_dev_tags( $query_args, $view_settings, $view_id ) {
 
    $types     = (array) $query_args['post_type'];
    $post_type = 'post';//This filter acts on the post type "post" 
    $act_view  = 4024;//This filter acts on the View with ID 4024
    $tag_ids   = [37];//We want to exclude Term ID 37
    $query_arg = 'tag__not_in'; 
    
    if(is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ))//Do NOT run this in the backend, but ensure it runs on AJAX     
        return $query_args;//Return existing query args
    
    if ( in_array( $post_type, $types ) && $view_id == $act_view ) {//Run this only when the View ID and Post Type match    
        $query_args[$query_arg] = $tag_ids; 
    } 

    return $query_args;//Return new query args

}

Finally we will need to set the Views Custom Search settings to “Show only filter options that would produce results”, so the Custom Search input as well reflects this change and shows only the Terms we want.