public
Last active

Determining if modifying the main query or not in WordPress

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
<?php
 
# See bigdawggi's comment below for a good combined example
 
// Pre-3.3
function cf_google_search_kill_wp_search( $where, $query ) {
global $wp_the_query;
 
if( ! is_admin() && $query->is_search() && $query === $wp_the_query ) {
$where = ' AND 1=0';
}
 
return $where;
}
add_filter( 'posts_where', 'cf_google_search_kill_wp_search', 10, 2 );
 
 
// Post-3.3
function cf_google_search_kill_wp_search( $where, $query ) {
if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) {
$where = ' AND 1=0';
}
 
return $where;
}
add_filter( 'posts_where', 'cf_google_search_kill_wp_search', 10, 2 );
 
?>

Glad to see an is_main_query() method, how 'bout this?

function cf_google_search_kill_wp_search( $where, $query ) {
    // We only modify non-admin AND search queries
    if (!is_admin() && $query->is_search()) {

        // 3.3 know-how for main query check
        if (method_exists($query, 'is_main_query')) {
            if ($query->is_main_query()) {
                $where = ' AND 1=0';
            }
        }
        else { // fall back to global to see if it's the main query
            global $wp_the_query;
            if ($query === $wp_the_query) {
                $where = ' AND 1=0';
            }
        }
    }

    // Return our possibly modified $where
    return $where;
}
add_filter('posts_where', 'cf_google_search_kill_wp_search', 10, 2);

Oops, I was missing the is_search() check in my example. I also meant to add onto $where rather than replacing it, but now that I think of it replacing is better.

But anyway, yeah, I like your example and that'll work well. :)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.