How can I apply pre_get_posts to a custom query?

For example, if I have:

$custom_query = new WP_Query(...)
//code here

How can I apply the pre_get_posts for this $custom_query?

2 Answers 2


For some use cases, couldn't you use $query->get() to target specific custom queries?

For example: say you've got a custom query for a slider post-type. Perhaps something like this?

function wpse64950_filter_pre_get_posts( $query ) {
    if ( ! is_main_query() ) {
        if ( 'slider' == $query->get( 'post-type' ) ) {
            // This is a query of slider posts,
            // and isn't the main query;
            // Do something
add_filter( 'pre_get_posts', 'wpse64950_filter_pre_get_posts' );

Granted, this will target every such slider post-type custom query; so it won't work in every case. But it should work in some cases.


pre_get_posts fires for every post query.

There is really no reason to apply it to a specific custom query. If you don't want it to be applied to your custom query you need to make sure you are checking for is_main_query().

  • I want it to be applied to a custom query, but not on the main query. Here's what i'm trying to achieve - i want to list posts with closed comments on one page, and i think it can be achieved with comment_status, 'open', using the pre_get_posts. On the other hand, i want to do that with just one custom query, while the main query should remain intact. Or is my logic wrong, and i'm missing something?
    – idjuradj
    Sep 12, 2012 at 17:12
  • 1
    Why don't you just pass the necessary parameters to that specific query, since you're setting it up anyway?
    – Pippin
    Sep 12, 2012 at 17:36
  • @Pippin - how would i do that in my case? I want the main parameter to be are comments open or not? so i want to create a query that will show only posts with closed or opened comments? How would i do that? Any help would be appreciated.
    – idjuradj
    Sep 12, 2012 at 19:03
  • You would do it in exactly the same way that you would with pre_get_posts. Do you know how to do it there (excluding the part about targeting a specific query)?
    – Pippin
    Sep 12, 2012 at 22:06
  • @Pippin Would it look something like this? function comm_cl( $query ) { $query->set( 'comment_status', 'open' ); } I had this bit of code, gist.github.com/3709991 - it is working, but it's not working well with pagination. So that's really the problem i'm trying to solve, and i was hoping i can achieve it with pre_get_posts. Any help on the matter would be appreciated.
    – idjuradj
    Sep 12, 2012 at 22:32

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.