WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.).

Any help would be much appreciated! Thanks.

share|improve this question
up vote 1 down vote accepted

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(
            'taxonomy' => 'region',
            'field' =>  'slug',
            'terms' => $user_region
    return $query;
add_filter( 'pre_get_posts', 'my_get_posts' );
share|improve this answer
Man, you're a life-saver and I'm an idiot. I was doing this, but I was checking on a single post page, which wasn't working. Then I looked in the sidebar and saw Recent Posts were filtered. Thanks for the nudge! My Full code is here (it was too long to fit here): [link]pastebin.com/WFuzWGzi – darrinb Jun 18 '11 at 23:13
Sorry I didn't get. is that not working for you? Or is it not working on single post page? – Hameedullah Khan Jun 19 '11 at 7:31
No, no, it's working great. I had a similar code in place, but I was literally looking in the wrong place. It don't filter out a single-post page though, which is fine. e.g., if you go to a url like: "domainname.com/2011/05/title-of-post"; that post will show regardless of the region associated with it. – darrinb Jun 22 '11 at 10:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.