Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
    
Why would you want to do this? Wouldn't this decrease the end user experience? –  m0r7if3r Feb 5 '12 at 17:31
    
@m0r7if3r No totally the opposite. The way my tax page is set up it'll provide a complete overview of the specific taxonomy term on the terms dedicated page. Which is why i'd like to, if possible, redirect the user –  Blackbird Feb 5 '12 at 17:45
add comment

2 Answers

up vote 1 down vote accepted

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 );
}
share|improve this answer
    
Works perfect! Thx –  Blackbird Mar 14 '12 at 16:35
add comment

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()

share|improve this answer
    
hmm no luck on this. Where should i past this code? At the top of my search.php file right? I assume i change $taxonomy with the right taxonomy? Thanks for the effort –  Blackbird Feb 6 '12 at 12:57
    
It would likely go there...code's completely untested, you may need to bang on it with a hammer a bit, see where it's failing. –  m0r7if3r Feb 6 '12 at 16:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.