1

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.

1 Answer 1

4

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(); ?>
3
  • 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, 2013 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, 2013 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, 2013 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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