Search Synonyms
Makes searches for one word also find posts that use another word with the same meaning, for example "sofa" also finds "couch", using groups you define.
Opens WPIDE on
Code
// Groups of words that mean the same thing on your site; a search for any of them finds them all. Empty = off. Examples:
// array( 'sofa', 'couch', 'settee' ),
// array( 'tv', 'television' ),
$wpide_search_synonyms = array();
add_filter( 'posts_search', function ( $search, $query ) use ( $wpide_search_synonyms ) {
global $wpdb;
if ( '' === $search || ! $wpide_search_synonyms || is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
return $search;
}
$terms = (array) $query->get( 'search_terms' );
// Leave exclusions ("-word") and exact-phrase searches to WordPress.
if ( ! $terms || $query->get( 'exact' ) || $query->get( 'sentence' ) || preg_grep( '/^-/', $terms ) ) {
return $search;
}
$lookup = array();
foreach ( $wpide_search_synonyms as $group ) {
$group = array_map( 'strtolower', array_map( 'trim', (array) $group ) );
foreach ( $group as $word ) {
$lookup[ $word ] = $group;
}
}
$changed = false;
$parts = array();
foreach ( $terms as $term ) {
$words = isset( $lookup[ strtolower( $term ) ] ) ? $lookup[ strtolower( $term ) ] : array( $term );
$ors = array();
$changed = $changed || count( $words ) > 1;
foreach ( $words as $word ) {
$like = '%' . $wpdb->esc_like( $word ) . '%';
$ors[] = $wpdb->prepare( "({$wpdb->posts}.post_title LIKE %s) OR ({$wpdb->posts}.post_excerpt LIKE %s) OR ({$wpdb->posts}.post_content LIKE %s)", $like, $like, $like );
}
$parts[] = '(' . implode( ' OR ', $ors ) . ')';
}
if ( ! $changed ) {
return $search;
}
$search = ' AND (' . implode( ' AND ', $parts ) . ') ';
if ( ! is_user_logged_in() ) {
$search .= " AND ({$wpdb->posts}.post_password = '') ";
}
return $search;
}, 10, 2 );
Notes
The list is empty by default; add groups of words. Searches with -exclusions or exact phrases are left to WordPress.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.