I have complicated query where I need to join multiple tables. I'm doing that via add_filter('posts_join') - my question is, when and where do I add the filter so that it only applies to the custom query?

My Custom Query

$test = new WP_Query(array('post_type' => 'artcpt', 'posts_per_page' => 10, 'tax_query' => array(array('taxonomy' => 'arttax', 'field' => 'id', 'terms' => array(20,41,16)))));

Should I physically add the filter above the query or after? Do I need to put it into a separate file (function.php) and attach it another way? Do I need to do something with query_vars?

1 Answer 1


You want to add your filter before you create the query:

add_filter( 'posts_join', 'custom_posts_join' );
$test = new WP_Query( $args );

where you can define the filter callback in your theme files, for example
functions.php or in a plugin:

function custom_posts_join( $join )
    // modifications
    // $join = ...

    // remove the filter 
    remove_filter( current_filter(), __FUNCTION__ );

    // return the result    
    return $join;


Notice that we remove the filter with this line:

    remove_filter( current_filter(), __FUNCTION__ );

so it will not affect other queries.

  • you post my exactly question 20 seconds before :) I deleted the mine and +1 the your. :)
    – gmazzap
    Commented Nov 25, 2013 at 19:58
  • @G.M. hehehe, thanks, but I was just trying to upvote your answer and was going to remove mine since it was very similar, I guess we had the same idea at the same time ;-)
    – birgire
    Commented Nov 25, 2013 at 19:59
  • What if the query is automatic? Like an archive template page, would I put the filter before wp_head()?
    – Howdy_McGee
    Commented Nov 25, 2013 at 22:08
  • If you want to filter the main query, you can for example add the above filter within a pre_get_posts action callback.
    – birgire
    Commented Nov 25, 2013 at 22:59

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.