If search matches taxonomy

Is it possible to redirect the user to the taxonomy page IF the search input matches the taxonomy name exactly?

For instance i have a taxonomy called “Actors”. If someone put into the search field “Tom Hanks” instead of going to the regular search page, it would redirect them to the taxonomy page for Tom hanks.

Related posts

Leave a Reply

2 comments

  1. I only wanted to match tags in a single taxonomy, so I was able to simplify the code as follows. My taxonomy is ‘post_tag’ — just swap yours out as needed.

    $i = 0;
    $search_query = get_search_query();
    
    $term = get_term_by( 'name', $search_query, 'post_tag' );
    if( $term !== false ) {
        $i++;
        $single_result = $term;
    }    
    
    if( $i == 1 && is_object( $single_result ) ) {
        $single_found = true;
    } else {
    $single_found = false;
    unset( $single_result );
    }
    
    if( $single_found ) {
        wp_redirect( get_bloginfo( 'url' ) . '/' . $single_result->slug );
    }
    
  2. How about something along these lines?

    $tax_args = array(
        'public' => true
    );
    $taxonomies = get_taxonomies( $tax_args, 'names', 'or' );
    
    $i = 0;
    foreach( $taxonomies as $tax ) {
        $term = get_term_by( 'name', $your_search_term, $taxonomy );
        if( $term !== false ) {
            $i++;
            $single_result = $term;
        }
    }
    
    if( $i === 1 && is_object( $single_result ) ) {
        $single_found = true;
    } else {
        $single_found = false;
        unset( $single_result );
    }
    
    if( $single_found ) {
        wp_redirect( get_bloginfo( 'url' ) . '/' . $single_result->taxonomy . '/' . $single_result->slug );
    }
    

    Docs: get_taxonomies(), get_term_by(), wp_redirect()