How to change the search action in wordpress search bar?
There's this addition to the SQL WHERE clause on wp-includes/class-wp-query.php:1306
:
<?php// wp-includes/class-wp-query.php:~1306foreach ( $q['search_terms'] as $term ) { //... $like = $n . $wpdb->esc_like( $term ) . $n; $search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s))", $like, $like, $like ); // ...
Therefore, I'd hook into the pre_get_posts
, and supply the words of the query as explicit "search_terms
", since they get added into that clause, with the LIKE
modifier just as you said were looking for!
So, we might do something like this:
<?php// functions.phpfunction fuzzify_query(\WP_Query $q) { if (true === $q->is_search() && true === property_exists($q, 'query') && true === key_exists('s', $q->query) ) { $original_query = $q->query['s']; $words = explode(' ', $original_query); $fuzzy_words = array_map( function($word) { return '%'.$word.'%'; }, $words ); $q->query_vars['search_terms'] = $fuzzy_words; return $q; } return $q;} add_action('pre_get_posts', 'fuzzify_query', 100); // Or whatever priority your fuzziness requires!