Send Searches That Match a Category to It
Takes shoppers straight to a product category page when what they search for is exactly a category name, such as "dresses" or "garden tools".
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_search() || 'product' !== get_query_var( 'post_type' ) || is_paged() ) {
return;
}
$term = get_term_by( 'name', trim( get_search_query( false ) ), 'product_cat' );
if ( ! $term ) {
$term = get_term_by( 'slug', sanitize_title( get_search_query( false ) ), 'product_cat' );
}
if ( $term && ! is_wp_error( $term ) ) {
$link = get_term_link( $term );
if ( ! is_wp_error( $link ) ) {
wp_safe_redirect( $link );
exit;
}
}
} );
Notes
Matching ignores upper and lower case, and partial matches still show the normal search results.
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.