Match Category and Tag Names in Search
Makes the site search also return posts whose categories or tags match the search words, so searching "recipes" finds everything filed under Recipes.
Opens WPIDE on
Code
// Taxonomies whose term names are searched.
$wpide_search_taxonomies = array( 'category', 'post_tag' );
add_filter( 'posts_search', function ( $search, $query ) use ( $wpide_search_taxonomies ) {
global $wpdb;
if ( '' === $search || is_admin() || ! $query->is_main_query() || ! $query->is_search() || ! $wpide_search_taxonomies ) {
return $search;
}
$taxonomies = "'" . implode( "','", array_map( 'esc_sql', $wpide_search_taxonomies ) ) . "'";
$pattern = '/\(' . preg_quote( $wpdb->posts, '/' ) . '\.post_title LIKE (\'(?:[^\'\\\\]|\\\\.)*\')\)/';
$result = preg_replace_callback( $pattern, function ( $m ) use ( $wpdb, $taxonomies ) {
return $m[0] . " OR ({$wpdb->posts}.ID IN (SELECT tr.object_id FROM {$wpdb->term_relationships} tr INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id WHERE tt.taxonomy IN ({$taxonomies}) AND t.name LIKE {$m[1]}))";
}, $search );
return null === $result ? $search : $result;
}, 10, 2 );
Notes
Add custom taxonomies to $wpide_search_taxonomies to include them too.
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.