WC_Product_Data_Store_CPT::search_products PHP Method

search_products() public method

Search product data for a term and return ids.
public search_products ( string $term, string $type = '', boolean $include_variations = false ) : array
$term string
$type string of product
$include_variations boolean in search or not
return array of ids
    public function search_products($term, $type = '', $include_variations = false)
    {
        global $wpdb;
        $search_fields = array_map('wc_clean', apply_filters('woocommerce_product_search_fields', array('_sku')));
        $like_term = '%' . $wpdb->esc_like($term) . '%';
        $post_types = $include_variations ? array('product', 'product_variation') : array('product');
        $type_join = '';
        $type_where = '';
        if ($type) {
            if (in_array($type, array('virtual', 'downloadable'))) {
                $type_join = " LEFT JOIN {$wpdb->postmeta} postmeta_type ON posts.ID = postmeta_type.post_id ";
                $type_where = " AND ( postmeta_type.meta_key = '_{$type}' AND postmeta_type.meta_value = 'yes' ) ";
            }
        }
        $product_ids = $wpdb->get_col($wpdb->prepare("\n\t\t\t\tSELECT DISTINCT posts.ID FROM {$wpdb->posts} posts\n\t\t\t\tLEFT JOIN {$wpdb->postmeta} postmeta ON posts.ID = postmeta.post_id\n\t\t\t\t{$type_join}\n\t\t\t\tWHERE (\n\t\t\t\t\tposts.post_title LIKE %s\n\t\t\t\t\tOR posts.post_content LIKE %s\n\t\t\t\t\tOR (\n\t\t\t\t\t\tpostmeta.meta_key = '_sku' AND postmeta.meta_value LIKE %s\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\tAND posts.post_type IN ('" . implode("','", $post_types) . "')\n\t\t\t\tAND posts.post_status = 'publish'\n\t\t\t\t{$type_where}\n\t\t\t\tORDER BY posts.post_parent ASC, posts.post_title ASC\n\t\t\t\t", $like_term, $like_term, $like_term));
        if (is_numeric($term)) {
            $product_ids[] = absint($term);
            $product_ids[] = get_post_parent($term);
        }
        return wp_parse_id_list($product_ids);
    }