MySQL FULLTEXT search for WordPress: natural language, boolean mode and relevance
WordPress search is a LIKE '%term%' on title, excerpt and content: no ranking beyond “title matches first”, no stemming, and a full table scan on every search. A FULLTEXT index on wp_posts gives MySQL a word index with relevance scores, and boolean mode adds required and excluded words and phrases. It needs a few settings to give good results, and it replaces the search query through a filter.
Problem: A site with 40,000 posts has a slow search (1.5 s per query) that ranks results poorly: a post that mentions the term once in a comment section of the content ranks like one about the topic. Phrase searches in quotes do not work as expected.
Solution: Add a FULLTEXT index on post_title and post_content, adjust the minimum word length and the stopword list where needed, replace the WHERE and ORDER BY of the main search query through the posts_search and posts_orderby filters with MATCH ... AGAINST, weight title matches higher, and use boolean mode for user input with quotes and minus signs.
The index
ALTER TABLE wp_posts ADD FULLTEXT INDEX ha_ft_title_content (post_title, post_content);
InnoDB supports FULLTEXT since MySQL 5.6 and MariaDB 10.0.5. Creating the index on a large table takes a while and rebuilds it; do it outside peak hours. A plugin that adds the index must remove it on uninstall, and core updates do not touch it.
Two settings decide which words are indexed:
[mysqld] innodb_ft_min_token_size = 2 # default 3: "UX", "AI", "IT" are not indexed otherwise innodb_ft_enable_stopword = ON # default stopword list: "the", "about", "will" ...
After changing innodb_ft_min_token_size, restart MySQL and rebuild the index (drop and add it again). MariaDB and MySQL have different variable names for the MyISAM variants (ft_min_word_len); for InnoDB tables, the innodb_ft_* settings apply.
Replace the search query
add_filter( 'posts_search', 'ha_fulltext_where', 10, 2 );
function ha_fulltext_where( string $search, WP_Query $query ): string {
global $wpdb;
if ( ! $query->is_main_query() || ! $query->is_search() || is_admin() ) {
return $search;
}
$term = $query->get( 's' );
return $wpdb->prepare(
" AND MATCH({$wpdb->posts}.post_title, {$wpdb->posts}.post_content) AGAINST (%s IN BOOLEAN MODE) ",
ha_boolean_query( $term )
);
}
add_filter( 'posts_orderby', 'ha_fulltext_orderby', 10, 2 );
function ha_fulltext_orderby( string $orderby, WP_Query $query ): string {
global $wpdb;
if ( ! $query->is_main_query() || ! $query->is_search() || is_admin() ) {
return $orderby;
}
$term = $query->get( 's' );
return $wpdb->prepare(
"( MATCH({$wpdb->posts}.post_title) AGAINST (%s) * 3 + MATCH({$wpdb->posts}.post_title, {$wpdb->posts}.post_content) AGAINST (%s) ) DESC",
$term,
$term
);
}
The WHERE part filters with boolean mode, the ORDER BY ranks with natural language mode, which returns a relevance score per row. The title-only MATCH needs its own index to work: add ALTER TABLE wp_posts ADD FULLTEXT INDEX ha_ft_title (post_title);. Multiplying it by 3 makes title matches count more than content matches.
Boolean mode for user input
function ha_boolean_query( string $input ): string {
$input = trim( preg_replace( '/[<>()~@]+/', ' ', $input ) ); // drop operators users rarely mean
if ( preg_match( '/"[^"]+"|^-|\s-/', $input ) ) {
return $input; // the user wrote a phrase or an exclusion: keep it
}
$words = preg_split( '/\s+/', $input, -1, PREG_SPLIT_NO_EMPTY );
return implode( ' ', array_map( fn( $w ) => '+' . $w . '*', $words ) );
}
Without operators, every word becomes required (+) with prefix matching (*): “wordpress cach” finds “caching”. Quoted phrases and -word exclusions from the user are passed through. Characters with special meaning in boolean mode that users type by accident (@, (, ~) are removed, because they can make MySQL reject the query.
NOTE: FULLTEXT search ignores words shorter than the minimum length and stopwords, and has no stemming or synonyms; a search for “cache” does not find “caching” without the prefix operator. For more, a search engine (Elasticsearch, OpenSearch, Meilisearch) behind a plugin is the next step. Whether the index is used: EXPLAIN for slow MySQL queries. A simple search across post content in PHP: get links to posts that contain a phrase.