erm_ids ) { global $wpdb; $meta_query_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' ); $tax_query_sql = $tax_query->get_sql( $wpdb->posts, 'ID' ); // Generate query. $query = array(); $query['select'] = "SELECT COUNT( DISTINCT {$wpdb->posts}.ID ) AS term_count, terms.term_id AS term_count_id"; $query['from'] = "FROM {$wpdb->posts}"; $query['join'] = " INNER JOIN {$wpdb->term_relationships} AS term_relationships ON {$wpdb->posts}.ID = term_relationships.object_id INNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id ) INNER JOIN {$wpdb->terms} AS terms USING( term_id ) " . $tax_query_sql['join'] . $meta_query_sql['join']; $term_ids_sql = $this->get_term_ids_sql( $term_ids ); $query['where'] = " WHERE {$wpdb->posts}.post_type IN ( 'product' ) AND {$wpdb->posts}.post_status = 'publish' {$tax_query_sql['where']} {$meta_query_sql['where']} AND terms.term_id IN $term_ids_sql"; $search_query_sql = \WC_Query::get_main_search_query_sql(); if ( $search_query_sql ) { $query['where'] .= ' AND ' . $search_query_sql; } $query['group_by'] = 'GROUP BY terms.term_id'; return $query; } /** * Formats a list of term ids as "(id,id,id)". * * @param array $term_ids The list of terms to format. * @return string The formatted list. */ private function get_term_ids_sql( $term_ids ) { return '(' . implode( ',', array_map( 'absint', $term_ids ) ) . ')'; } }