1

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.

1 Answer 1

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' );
3
  • 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, 2011 at 23:13
  • Sorry I didn't get. is that not working for you? Or is it not working on single post page? Jun 19, 2011 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, 2011 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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