How to detect custom query inside `posts_where` hook?

Imagine you have something like this:

function f_posts_where( $where ){
// set a condition based on arguments ...    
}

add_filter( 'posts_where', 'f_posts_where' );

What is the best way to set a condition for my custom query inside the f_posts_where?

I create a custom query like this:

$q = new \WP_Query( $args );

1 Answer
1

If we have the query arguments like this

$args = array(
  'queryid' => 'blackjack',
   ...    
);
$q = new WP_Query( $args );

Note we added one custom query argument that is not officially present in here.
Now we can identify the exact query by that queryid if we use the second parameter of the posts_where hook.

function f_posts_where( $where,  \WP_Query $q ){
  // $q->query will hold the query arguments ...
  if ( 'blackjack' == $q->query['queryid'] ){
    // do our custom actions on $where for our queryid blackjack
    return $where.
  }
 return $where;
}

add_filter( 'posts_where', 'f_posts_where', 10 , 2 );

As you can note $q->query will hold the query arguments.

This will allow us to intercept the custom queries we like if we add custom arguments we like. In this case the queryid.

Leave a Comment