public static function get_main_search_query_sql() { global $wp_the_query, $wpdb; $args = $wp_the_query->query_vars; $search_terms = isset($args['search_terms']) ? $args['search_terms'] : array(); $sql = array(); foreach ($search_terms as $term) { // Terms prefixed with '-' should be excluded. $include = '-' !== substr($term, 0, 1); if ($include) { $like_op = 'LIKE'; $andor_op = 'OR'; } else { $like_op = 'NOT LIKE'; $andor_op = 'AND'; $term = substr($term, 1); } $like = '%' . $wpdb->esc_like($term) . '%'; $sql[] = $wpdb->prepare("(({$wpdb->posts}.post_title {$like_op} %s) {$andor_op} ({$wpdb->posts}.post_excerpt {$like_op} %s) {$andor_op} ({$wpdb->posts}.post_content {$like_op} %s))", $like, $like, $like); } if (!empty($sql) && !is_user_logged_in()) { $sql[] = "({$wpdb->posts}.post_password = '')"; } return implode(' AND ', $sql); }
/** * 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'); }