I was reading Stephen Harris‘s excellent answer to this question regarding the use of WP_query()
, query_posts()
and pre_get_posts
.
He says “pre_get_posts is a filter, for altering any query. It is most often used to alter only the ‘main query’.”
It is possible to use pre_get_posts
to filter only a specific secondary query created with WP_Query
? eg.
$my_secondary_loop = new WP_Query(...);
if( $my_secondary_loop->have_posts() ):
while( $my_secondary_loop->have_posts() ): $my_secondary_loop->the_post();
//The secondary loop
endwhile;
endif;
wp_reset_postdata();
Any help much appreciated.
The simplest way is to add the action right before the query and remove it immediately after.
EDIT
Another technique you can use is to set your own query var and check for that in a hook:
and in the template:
With that being said unless you exclude your filter use the conditional:
is_main_query()
then your filter will fire on your new WP_Query.If you only want to target your specific new WP_Query then there is no way to do that.