Show matching terms in your search results

WordPress’ internal search isn’t all that great out of the box, as I’ve discussed before. For instance, tags and categories aren’t included in the search query; as such, if your post is tagged “apple”, but there is no mention of “apple” in the title or post content, the post won’t be included in your search results.

One partial workaround is to search taxonomy terms against your query and include those in your results. I did this previously with the CUNY J-School’s tech website:

You can have something similar with the code snippet below.

<?php
/**
 * Show matching terms for a given search query
 * Best placed under the_search_form() in search.php 
 */
global $wp_query;
// Only show the matching terms on the first page of results
if ( $wp_query->query_vars['paged'] <= 1 ) {
	$args = array(
		'search' => get_search_query(),
		'orderby' => 'none',
	);
	// You can change the first argument to an array of whatever taxonomies you want to search against
	$matching_terms = get_terms( array( 'post_tag', 'category' ), $args );
	if ( count( $matching_terms ) ) {					
		echo '<div class="all-matching-terms">Looking for? ';
		$all_terms = '';
		foreach ( $matching_terms as $matching_term ) {
			$all_terms .= '<a ';
			if ( $matching_term->description )
				$all_terms .= 'title="' . esc_attr( $matching_term->description ) . '" ';
			$all_terms .= 'href="' . esc_url( get_term_link( $matching_term, $matching_term->taxonomy ) ) . '">' . esc_html( $matching_term->name ) . '</a>, ';
		}
		echo rtrim( $all_terms, ', ' );
		echo '</div>';
	}
}

Author: Daniel Bachhuber

Proud father x2. Principal, Hand Built. Maintainer, WP-CLI.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s