WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Tags are a major part of my platform. Using the default search, if the search term matches a tag, on the results page, I want it to display:

<p>Are you looking for our <a href="TAG-URL">TAG-Name</a> page?</p>

The tag must have at least one post attached to it, so no empty tags. What would be the lightest solution to achieve this? Our search feature is used very frequently.

share|improve this question
up vote 4 down vote accepted

In functions.php:

function wpse82525_link_search_to_tag()
    // check if search archive is being displayed
    if( ! is_search() )

    // get search query var
    $sqv = get_query_var( 's' );

    // get tag base
    $tagbase = get_option( 'permalink_structure' ) 
        ? get_option( 'tag_base' ) 
            ? trailingslashit( get_option( 'tag_base' ) )
            : 'tag/' 
        : '?tag=';

    // return link if matching tag is found
    return ( get_term_by( 'slug', $sqv, 'post_tag' ) )
        ? '<p>' . sprintf( 
            __( 'Are you looking for our <a href="%1$s">%2$s</a> page?', 'txtdomain' ),
            home_url( $tagbase . sanitize_title_with_dashes( $sqv ) ),
        ) . '</p>'
        : '';

In search.php:

<?php echo wpse82525_link_search_to_tag(); ?>
share|improve this answer
Excellent answer, only one problem. I want to exclude tags that have no posts attached to them. Is this possible? Because currently it lists tags that are empty as well. – Christine Cooper Jan 22 '13 at 14:35
Sure! Just replace return ( get_term_by( 'slug', $sqv, 'post_tag' ) ) with $obj = get_term_by( 'slug', $sqv, 'post_tag' ); return ( $obj && $obj->count >= 1 ) – diggy Jan 22 '13 at 18:08
It is clear that you seem to be in full control of your coding skills - works perfectly, Answer accepted. – Christine Cooper Jan 22 '13 at 18:40

Your Answer


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.