Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

1 Answer 1

up vote 2 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

 
discard

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.