Filter all queries with a specific taxonomy

Is there any way to filter all post queries and add a specific taxonomy? Case in point, I have a taxonomy object of “Region” with terms like “Global”, “Americas”, “Europe”, etc. (Users designate their region in their user profile through custom fields which is stored as a usermeta value and added the user cache object.)

The idea being that as the signed-in user navigates the site, they’d only see content designated within their region. Obviously I could write a custom query per page to include their region, but I was wondering if there was a way to tap into the query object and add the taxonomy requirement regardless of what the query was for (e.g, post, custom post type, archive page, etc.).

Read More

Any help would be much appreciated! Thanks.

Related posts

Leave a Reply

1 comment

  1. Below code is an example that does what you want. See tax_query for more information.

    function my_get_posts( $query ) {
        // we only need to modify the query for logged in users
        if ( !is_user_logged_in() ) return $query;
        $current_user = wp_get_current_user();
        // assuming that user's region is stored as user_region meta key
        $user_region = get_user_meta( $current_user->ID, 'user_region', true );
        $query->set( 'tax_query', array(
            array(
                'taxonomy' => 'region',
                'field' =>  'slug',
                'terms' => $user_region
            )
        ));
        return $query;
    }
    add_filter( 'pre_get_posts', 'my_get_posts' );