• Hi all,

    I have written a search for a blog. In this blog there are a lot of posts with movies and photos. In a normal search query all fields, including the content field, are returned. That is devastating for performance. That is why I wrote a hack in query.php.
    The hack consists of three lines of code and is a big improvement for performance. I just added an extra case in the switch statement for deciding which fields are returned in the query:
    ´switch ( $q[‘fields’] ) {
    case ‘ids’:
    $fields = “$wpdb->posts.ID”;
    break;
    case ‘id=>parent’:
    $fields = “$wpdb->posts.ID, $wpdb->posts.post_parent”;
    break;
    case ‘searchOptimization’:
    $fields = “$wpdb->posts.ID, $wpdb->posts.post_title, wpdb->posts.post_excerpt”;
    break;
    default:
    $fields = “$wpdb->posts.*”;
    }`

    I have implemented two ways to get to the case ‘searchOptimization’:
    The first is this code directly ahead of the previous switch statement, hence in query.php as well:

    if($q['taxonomy']== 'post_tag' || $q['search'] == 'Zoek'){
      $q['fields'] = 'searchOptimization';
    }

    Zoek is the value of the button of the searchform.php and is Dutch for ‘Search’.

    The second method is to add a filter in the functions.php of the theme:

    function alter_the_query( $request ) {
      if ( array_key_exists('s', $request) ){
        $request['order'] = 'ASC';
        $request['orderby'] = 'title';
        $request['fields'] = 'searchOptimization';
      }
      if ( array_key_exists('taxonomy', $request) ){
        $request['order'] = 'ASC';
        $request['orderby'] = 'title';
        $request['fields'] = 'searchOptimization';
      }
      return $request;
    }
    add_filter( 'request', 'alter_the_query' );

    What do you think of this idea?
    Is it a good idea to enhance the switch statement with this selection of fields? Are the statements right before the switch statements the best solution? Or the filter in the functions.php?
    Or is there another way to prevent WordPress to return all fields – most important of all the content field – in the query?

    With kind regards,

    Loek Bergman

  • The topic ‘optimizing search query selecting small field set – hack of query.php’ is closed to new replies.