How to pass custom parameter to WP_Query for filtering in pre_get_posts

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