How to pass custom parameter to WP_Query for filtering in pre_get_posts

I have an ajax request that returns the result of a WP_Query loop.

I would like to detect in pre_get_posts filter the specific wp_query instance that is used in the ajax handler.

I thought placing a custom parameter in the $args of the WP_Query in the ajax handler:

$args= array(...,
            'ajax' => 'AJAX',//custom param for detection of specific WP_Query instance
            ....);

and by this way detecting the specific instance in pre_get_post:

 if(isset($query->query_vars['ajax']){
    Do stuff
 }

I do not know if this has any sense to you…

Thanks¡¡

1 Answer
1

You can access query variables (including custom ones) via the WP_Query::get() method.

For example:

$my_query = new WP_Query( array(
      ...
      'wpse105219_custom_var' => 'foobar',
      ...
) );

To ‘catch’ this at pre_get_posts:

add_action( 'pre_get_posts', 'wpse105219_pre_get_posts', 10 );
function wpse105219_pre_get_posts( $query ){
      if( $query->get( 'wpse105219_custom_var' ) == 'foobar' ){
         //Alter $query
      }
}

Leave a Comment