/** * Count products within certain terms, taking the main WP query into consideration. * * @param array $term_ids * @param string $taxonomy * @param string $query_type * @return array */ protected function get_filtered_term_product_counts($term_ids, $taxonomy, $query_type) { global $wpdb; $tax_query = WC_Query::get_main_tax_query(); $meta_query = WC_Query::get_main_meta_query(); if ('or' === $query_type) { foreach ($tax_query as $key => $query) { if (is_array($query) && $taxonomy === $query['taxonomy']) { unset($tax_query[$key]); } } } $meta_query = new WP_Meta_Query($meta_query); $tax_query = new WP_Tax_Query($tax_query); $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'] = "\n\t\t\tINNER JOIN {$wpdb->term_relationships} AS term_relationships ON {$wpdb->posts}.ID = term_relationships.object_id\n\t\t\tINNER JOIN {$wpdb->term_taxonomy} AS term_taxonomy USING( term_taxonomy_id )\n\t\t\tINNER JOIN {$wpdb->terms} AS terms USING( term_id )\n\t\t\t" . $tax_query_sql['join'] . $meta_query_sql['join']; $query['where'] = "\n\t\t\tWHERE {$wpdb->posts}.post_type IN ( 'product' )\n\t\t\tAND {$wpdb->posts}.post_status = 'publish'\n\t\t\t" . $tax_query_sql['where'] . $meta_query_sql['where'] . "\n\t\t\tAND terms.term_id IN (" . implode(',', array_map('absint', $term_ids)) . ")\n\t\t"; if ($search = WC_Query::get_main_search_query_sql()) { $query['where'] .= ' AND ' . $search; } $query['group_by'] = "GROUP BY terms.term_id"; $query = apply_filters('woocommerce_get_filtered_term_product_counts_query', $query); $query = implode(' ', $query); $results = $wpdb->get_results($query); return wp_list_pluck($results, 'term_count', 'term_count_id'); }