Combining WP_Query Search & Taxonomy  Parameters

Search within a taxonomy by patching the way WP_Query handles the MySQL GROUP BY clause.

WP_Query is the primary way to write custom queries in WordPress. If you’re having trouble combining a search value (s argument) and taxonomy query (tax_query argument) using WP_Query try using the following class to solve the issue.

/**
 * Search Within a Taxonomy
 * 
 * Support search with tax_query args
 *
 * $query = new WP_Query( array(
 *  'search_tax_query' => true,
 *  's' => $keywords,
 *  'tax_query' => array( array(
 *      'taxonomy' => 'country',               
 *      'field' => 'id',                      
 *      'terms' => $country,   
 *  ) ),
 * ) );
 */
class WP_Query_Taxonomy_Search {
    public function __construct() {
        add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
    }

    public function pre_get_posts( $q ) {
        if ( is_admin() ) return;

        $wp_query_search_tax_query = filter_var( 
            $q->get( 'search_tax_query' ), 
            FILTER_VALIDATE_BOOLEAN 
        );

        // WP_Query has 'tax_query', 's' and custom 'search_tax_query' argument passed
        if ( $wp_query_search_tax_query && $q->get( 'tax_query' ) && $q->get( 's' ) ) {
            add_filter( 'posts_groupby', array( $this, 'posts_groupby' ), 10, 1 );
        }
    }

    public function posts_groupby( $groupby ) {
        return '';
    }
}

new WP_Query_Taxonomy_Search();

Now you can add the custom search_tax_query to WP_Query objects that you want this functionality added to. For example:

$query = new WP_Query( array(
    'search_tax_query' => true,
    's' => $keywords,
    'tax_query' => array( array(
        'taxonomy' => 'country',               
        'field' => 'id',                      
        'terms' => $country,   
    ) ),
) );

The underlying problem is a result of a problematic GROUP BY clause that is added by the WP_Query class when a tax_query parameter is present. This conflicts with the s parameter, resulting in no results found. By removing the GROUP BY clause entirely we are able to solve the issue.

Related Articles

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 16 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.