0

This question already has an answer here:

I've done a wp_query in a shortcode. So, in page xyz I've two wp queries, one is the main query, and other's mine. The SQL query that I got from the query doesn't fit my desired affect. So I need to filter the query clauses to inject my conditions (I think that's the only way I've now, even though it's my custom query). All the answers I've got are using pre_get_posts with a $this->is_main_query(), but that doesn't fit my case, I think.

How can I target that specific query using posts_clauses filter?

I've seen a random number in query_vars_hash like 281f08ffcd75c8.... Is that a unique identifier so that I can specifically target my specific query?

marked as duplicate by Howdy_McGee, fuxia Jun 4 '16 at 14:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Did you consider reversing the check to $this->is_main_query() == false? What are you trying to do that your query isn't doing? Can you edit your question to include the second query mentioned? – Tom J Nowell May 31 '16 at 20:28
  • I want to push a meta query conditionally that acts with the posts table with an OR. But typically a meta query added with posts query with an AND. Therefore I did it using Howdy's answer, using posts_clauses filter. – Abirvab Jun 3 '16 at 9:06
3

One of the easier ways to do this is to just add the filter before your query and remove it after:

add_filter( 'posts_orderby', 'filter_function' );

    $something = new WP_Query( $args );

remove_filter( 'posts_orderby', 'filter_function' );

Then you can just add your function into functions.php as normal:

/**
 * The below function filters something
 * Added inline on template blah.php
 */
function filter_function() {
    // Things n' stuff
}

You could also ( if you wanted to use pre_get_posts ) target not main queries:

if( ! $query->is_main_query() ) { /* ... */ }

Or as Milo suggests in an old answer - set a query var that your WP_Query will specifically use.

3

My preference is a special query var that acts as a flag to trigger your filter:

function wpse_228386_maybe_batman( $clauses, $wp_query ) {
    if ( $wp_query->get( 'iamthebatman' ) ) {
        // Fight crime
    }

    return $clauses;
}

add_filter( 'posts_clauses', 'wpse_228386_maybe_batman', 10, 2 );

Now you can "activate" it anywhere you like, without needing to add/remove the filter every time:

$query = new WP_Query([ 'iamthebatman' => true ]);

Just make sure that whatever query var you pick, it's specific and unique to your project, and that it doesn't clash with WordPress reserved terms.

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