WC_Query::has_positive_search_terms
Check whether the current search query contains at least one positive (non-exclusion) term.
WordPress relevance ordering requires positive search terms to build a valid ORDER BY clause. Searches that are empty or contain only exclusion terms (e.g. "-condebug") produce no positive terms, which results in invalid SQL when relevance ordering is used.
This method delegates tokenization to WP_Query so it correctly handles WordPress's search term parsing (splitting on spaces, commas, and +) and respects the wp_query_search_exclusion_prefix filter.
Method of the class: WC_Query{}
Hooks from the method
Returns
true|false.
Usage
// private - for code of main (parent) class only $result = $this->has_positive_search_terms(): bool;
WC_Query::has_positive_search_terms() WC Query::has positive search terms code WC 10.8.1
private function has_positive_search_terms(): bool {
$search_string = get_query_var( 's' );
$search_string = is_array( $search_string ) ? '' : trim( (string) $search_string );
if ( '' === $search_string ) {
return false;
}
// Use WP_Query to parse search terms using core's tokenization rules.
$search_query = new class( array( 's' => $search_string ) ) extends \WP_Query {
/**
* This constructor is overridden to avoid triggering a database query while allowing access to search term parsing routines.
* Using public query APIs such as the `parse_query` method leads to test regressions, so an anonymous class approach is used instead.
*
* @param string|array $query URL query string or array of vars.
*/
public function __construct( $query = '' ) {
$this->query_vars = (array) $query;
$this->parse_search( $this->query_vars );
}
};
$search_terms = $search_query->query_vars['search_terms'] ?? array();
if ( empty( $search_terms ) ) {
return false;
}
/** This filter is documented in wp-includes/class-wp-query.php */
$exclusion_prefix = (string) apply_filters( 'wp_query_search_exclusion_prefix', '-' ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment
if ( '' !== $exclusion_prefix ) {
$search_terms = array_filter(
$search_terms,
static fn( $term ) => ! str_starts_with( $term, $exclusion_prefix )
);
}
return ! empty( $search_terms );
}