". /** * 1) Ignore bogus product_cat=0 some search forms submit * and force search to products (optional). */ add_action('pre_get_posts', 'd10_fix_search_product_cat_zero', 5); function d10_fix_search_product_cat_zero( $q ){ if ( is_admin() ) return; if ( ! ($q instanceof WP_Query) ) return; if ( ! $q->is_main_query() ) return; if ( ! $q->is_search() ) return; // If the form sent product_cat=0, remove it $pc = $q->get('product_cat'); if ( $pc === '0' || $pc === 0 ) { $q->set('product_cat', '' ); // Also scrub tax_query clauses that target product_cat=0 $tax_query = (array) $q->get('tax_query'); if ( $tax_query ) { $new = array(); foreach ( $tax_query as $clause ) { if ( is_array($clause) && isset($clause['taxonomy']) && $clause['taxonomy'] === 'product_cat' && isset($clause['terms']) && ( $clause['terms'] === 0 || $clause['terms'] === '0' $clause['terms'] === array(0) $clause['terms'] === array('0') ) ) { // skip this clause continue; } $new[] = $clause; } $q->set('tax_query', $new); } } // Optional: keep search limited to products $q->set('post_type', array('product')); } /** * 2) Join tag tables so search can match product_tag name/slug */ add_filter('posts_join', 'd10_search_join_tags', 10, 2); function d10_search_join_tags( $join, $q ){ if ( is_admin() ! $q->is_main_query() ! $q->is_search() ) return $join; global $wpdb; if ( strpos($join, "{$wpdb->term_relationships}") === false ) { $join .= " LEFT JOIN {$wpdb->term_relationships} tr ON (tr.object_id = {$wpdb->posts}.ID)"; } if ( strpos($join, "{$wpdb->term_taxonomy}") === false ) { $join .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON (tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy='product_tag')"; } if ( strpos($join, "{$wpdb->terms}") === false ) { $join .= " LEFT JOIN {$wpdb->terms} t ON (t.term_id = tt.term_id)"; } return $join; } /** * 3) Extend WHERE to include tag name/slug LIKE the search term */ add_filter('posts_where', 'd10_search_where_tags', 10, 2); function d10_search_where_tags( $where, $q ){ if ( is_admin() ! $q->is_main_query() ! $q->is_search() ) return $where; global $wpdb; $term = $q->get('s'); if ( ! $term ) return $where; $like = '%' . $wpdb->esc_like($term) . '%'; $where .= $wpdb->prepare( " OR (tt.taxonomy='product_tag' AND (t.name LIKE %s OR t.slug LIKE %s))", $like, $like ); return $where; } /** * 4) Avoid duplicates when multiple tags match */ add_filter('posts_distinct', 'd10_search_distinct', 10, 2); function d10_search_distinct( $distinct, $q ){ if ( is_admin() ! $q->is_main_query() ! $q->is_search() ) return $distinct; return 'DISTINCT'; }