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
?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityHow 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
?
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
}
}
return;
}
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.
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().
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.