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.

[sourcecode lang=”php”]<?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>’;
}
}[/sourcecode]

Leave a comment

Your email address will not be published. Required fields are marked *