overwrite the search function in wordpress (sql an

2019-04-14 16:15发布

问题:

Is there a way to overwrite the default search function in wordpress? I have tried using the filters, but they only allow adding to the query... or possibly rewriting the whole query using posts_request. If I overwrite that though, no other querys will work. I have the following code

function my_posts_request_filter($input)
{
    if ( is_search() && isset($_GET['s'])) {
        global $wpdb;
    }
    return $input;
}

add_filter('posts_request','my_posts_request_filter');

I could override $input with my custom SQL, but there is a widget on the page which shows recent posts and that wouldn't show if I do this. Is there a way to JUST overwrite the search function??

回答1:

This isn't bulletproof, but assuming the first WP_Query call is for the search request (there might be a scenario where a plugin calls it before WordPress does, but it is unlikely), you can strip the filter once the function runs.

function my_posts_request_filter($input)
{
    if ( is_search() && isset($_GET['s'])) {
        global $wpdb;

        // do your funky SQL

        remove_filter('posts_request','my_posts_request_filter');
    }
    return $input;
}