Wordpress - How to prevent execution of default query, while preserving ability to use WP_Query in template?
I know it might be abit late for answer but I came across similar issue while making my test project. Here's how I solved it.
/* apply this filter only on relevant to you pages */
function mb_bail_main_wp_query( $sql, WP_Query $wpQuery ) {
if ( $wpQuery->is_main_query() ) {
/* prevent SELECT FOUND_ROWS() query*/
$wpQuery->query_vars['no_found_rows'] = true;
/* prevent post term and meta cache update queries */
$wpQuery->query_vars['cache_results'] = false;
return false;
}
return $sql;
}
add_filter( 'posts_request', 'mb_bail_main_wp_query', 10, 2 );
@UPDATE:
Changed code to use normal function instead of anonymous one and made made code return 'false' instead of 'SELECT 0 AS ID' as it caused to return one dummy empty WP_Post object. Returning 'false' makes $wpdb->get_results() to bail early so no query is made.
Completely canceling main query is pretty much high level madness, that involves subclassing wp
class.
I would:
- Hook into
pre_get_posts
withis_main_query()
check - Run featured query (still inside hook) and stash results somewhere
- Use those results to set excluded posts on main query