miguel.nz

Include taxonomy terms on your WP_Query search

April 6, 2022   |   1 minute read.

I have been looking for a way to search use the search_query with the WP_Query and include taxonomy terms.

Many solutions only works using the function is_search(). Using the tax_query for me was not an option here as I wanted to use the search query field “s” to search under the post_content, title and be able to work with other search plugins as well.

The following filter will help you to achieve that:

function extend_search_taxonomy_terms( $search, $wp_query ) {
  global $wpdb;

  if ( empty($search) ) {
    return $search;
  }

  $terms = $wp_query->query_vars['s'];
  $exploded = explode( ' ', $terms );
  
  if( $exploded === FALSE || count( $exploded ) == 0 ) {
    $exploded = array( 0 => $terms );
  }

  $search = '';
    
  foreach( $exploded as $tag ) {
    $search .= " AND (
      ( $wpdb->posts.post_title LIKE '%$tag%' )
      OR EXISTS
      ( SELECT * FROM $wpdb->term_relationships 
        LEFT JOIN $wpdb->terms ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->terms.term_id
        WHERE $wpdb->terms.name LIKE '%$tag%' AND $wpdb->term_relationships.object_id = $wpdb->posts.ID
      )
    )";
  }
  return $search;
}

Then you have to add this filter whenever you need it:


// Add your filter
add_filter('posts_search', 'extend_search_taxonomy_terms', 500, 2);

$args = array(
 's' => 'foo',
 'post_type' => 'my-post-type'
);

$the_query = new WP_Query($args);

if ($the_query->have_posts()) {
  // Loop your posts
}

// Remove your filter
remove_filter('posts_search', 'extend_search_taxonomy_terms', 500, 2);

From: https://stackoverflow.com/questions/13491828/how-to-amend-wordpress-search-so-it-queries-taxonomy-terms-and-category-terms