2

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 );
3

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.

| improve this answer | |
  • yes custom query arguments can be handy. There's a getter for it WP_Query::get() so we could use $q->get( 'queryid' ). When I use it I sometimes prefix the arguments with wpse_ or just underscore (e.g. here), to avoid possible name collision in the future. – birgire Jan 14 '17 at 14:22
  • @birgire: Maybe one-day query argument _id become part of the codex and part of the default query arguments. – prosti Jan 14 '17 at 16:21
  • Based on your idea, any query may have the _id for instance main-search may be one nice name. – prosti Jan 14 '17 at 17:01
  • 1
    I've learned a lot from this site, so I try to pass it on when I can ;-) Here's a discussion on the general automatic approach. – birgire Jan 14 '17 at 17:38
  • 1
    Wow, thank you- this is the first I've heard of custom query arguments, and using a custom queryid to limit/scope a filter function is brilliant! – nickpish Sep 17 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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