Quantcast
Viewing latest article 2
Browse Latest Browse All 10

wordpress:Add relevant tag to search results

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:

1
<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.

Answers

In functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

1
<?php echo wpse82525_link_search_to_tag(); ?>
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.
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 )
It is clear that you seem to be in full control of your coding skills – works perfectly, Answer accepted.

Source


Viewing latest article 2
Browse Latest Browse All 10

Trending Articles