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.

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
add comment

1 Answer

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

    // 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 ) ),
            $sqv
        ) . '</p>'
        : '';
}

In search.php:

<?php echo wpse82525_link_search_to_tag(); ?>
share|improve this answer
1  
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
1  
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
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.