Replace/Mute/Stop Search Query

I'm trying to replace the search functionality in WP.

I've already created the search.php template with all the results I want to display.

I don't want any results from the WP database. I just want to show my results in search.php using the native searchform.php and the native ?s=keyword URL structure.

Doing that because of SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts ... search built in query with is very CPU consuming.

So in my themes functions.php I added:

add_action('pre_get_posts', 'no_search_query');
function no_search_query($query) {
    if($query-is_search()  $query-is_main_query()  get_query_var('s', false)) {
        unset( $query-query_vars['s'] );
        $query-set( 'post__in', '' );
    }
}

and added:

$is_search_query = ($_GET["s"]) ? ($_GET["s"]) : 0;

to my search.php to get the search keyword.

This actually did the trick but the query is still being called.

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts  WHERE 1=1  AND wp_posts.post_type IN ...

The call to the database is now a lot of less consuming (there are no arguments) but its still a call to the database which I want to eliminate.

Any idea how to do that?

Best regards.

Topic pre-get-posts search-engines database query Wordpress search

Category Web


I had a quick grep for SQL_CALC_FOUND_ROWS and found a few instances. I'm not sure which one is being called in your case, but here's an interesting one from wp-includes/class-wp-query.php line 2904 onwards:

$found_rows = '';
if ( ! $q['no_found_rows'] && ! empty( $limits ) ) {
  $found_rows = 'SQL_CALC_FOUND_ROWS';
}

$old_request   = "SELECT $found_rows $distinct $fields FROM {$wpdb->posts} $join WHERE 1=1 $where $groupby $orderby $limits";
$this->request = $old_request;

if ( ! $q['suppress_filters'] ) {
  /**
   * Filters the completed SQL query before sending.
   *
   * @since 2.0.0
   *
   * @param string   $request The complete SQL query.
   * @param WP_Query $this    The WP_Query instance (passed by reference).
   */
  $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
}

The important part is that there's a filter here where you get the SQL and you can do your own checks on it. It doesn't look like you can stop the query running, but at least you could change the SQL to something that doesn't bother you ;-)

I don't know what the suppress_filters flag is here, so you'll need to make sure that that isn't set.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.