Last Updated:

Add the name of the taxonomy (term) to the search for records

Task: to the standard search for products, you need to add a search by the name of the product attribute. In other words, you need to add to the default search for goods products that relate to the attribute "Manufacturer" from the search phrase.

The logic of the work is as follows:

  • We search in the taxonomy (attribute) "Producer" terms by search phrase
  • Request all records related to found manufacturers
  • Add found records to the shared record pool that was found as standard

This mechanism can also be used to search for any types of records and taxonomies - change them in the code to the desired ones.

 init new Post_Search_With_Terms( [ 'post_type' => 'product', 'taxonomy' => 'pa_izgotovitel' ] ); /** * Extends default posts search in order to search by terms titles too. * * @version: 1.0 */ final class Post_Search_With_Terms  { private $post_type; private $taxonomy; /** * @param array $args { * Arguments to retreive posts. * * @type string $post_type Default: post * @type string $taxonomy Default: post_tag * } */ public function __construct( $args = [] ) { $args = (object) array_merge( [  'post_type' => 'post', 'taxonomy' => 'post_tag' ], $args ); foreach( $args as $key => $val ){ $this->$ key = $val; } add_filter( 'pre_get_posts', [ $this, 'extends_search_query' ] ); } /** * @param WP_Query $wp_query */ public function extends_search_query( $wp_query ) {  Only for the basic if query  ( ! $wp_query->is_main_query() ) { return; }  Only for the specified post type if ( ! $wp_query->is_post_type_archive ( $this->post_type )  ) { return; }  To search the front if ( ! is_admin() && $wp_query->is_search() ) { add_filter( 'posts_where', [ $this, ' add_tax_query' ] ); }  To search the admin panel if ( is_admin() ) { add_filter ( 'posts_where', [ $this, 'add_tax_query' ] ];  } }  /** * Returns the terms of the specified taxonomy based on the search query. * * @return WP_Term[]|array Empty array if no terms found. */ private function search_terms() { $search_query = filter_input( INPUT_GET, 's' ); if ( empty( $search_query ) ) { return []; } $terms = get_terms( [ 'taxonomy' => $this->taxonomy, 'name__like' => $search_query, ] ); return is_wp_error( $terms ) ? [] : $terms; } /** * Adds extended sampling conditions to the base query for the specified taxonomy. * * @param string $where * *  @return string */ public function add_tax_query( $where ) { global $wpdb; $terms = $this->search_terms(); if ( $terms ) { $ids = implode( ',', wp_list_pluck( $terms, 'term_id' ) ); $ where . = " OR ID IN (SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ($ids) )"; }  Undo the filter so that it is not applied to other requests remove_filter( 'posts_where', [ $this, __FUNCTION__ ] );  return $where;
	}
}