WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to run custom sql for search results, and I'm having trouble limiting the filter to the main query without running a redundant query.

I'm successfully getting results via the following:

add_filter( 'posts_request', 'my_request_filter' );

function my_request_filter($sql) {
    if(is_search()) {
        $sql = 'some custom sql query'
    return $sql;

The problem here is that this is affecting other things on the page running queries, like the recent posts widget. I can prevent this by adding 'suppress_filters' => true to the other queries, but that seems a bit backwards, and I'm not going to hack core to add that.

the 'pre_get_posts' filter seems more appropriate, in that I can check for is_main_query, but I'm limited in how I can modify the query with this filter - I can't figure out how to entirely replace the query object with one created by a custom sql statement.

The least ideal solution would be to simply ignore the main query, and run another one entirely; but the whole point of this exercise was to replace the main query with one optimized for this context.

share|improve this question
up vote 3 down vote accepted

The posts_request filter actually takes a second argument, which is the query. You can check if that query is the main query. Try this:

add_filter( 'posts_request', 'my_request_filter', 10, 2 );

function my_request_filter($sql, $query) {
    if($query->is_main_query() && is_search()) {
        $sql = 'some custom sql query'
    return $sql;
share|improve this answer
that's exactly it - thanks! – elleeott Oct 24 '12 at 17:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.