When to add_filter() to Custom Query

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

Read More
$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?

Related posts

1 comment

  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.

Comments are closed.