This question already has an answer here: Handling a custom taxonomy in WooCommerce wc_get_products function (1 answer) Closed 4 hours ago. I have products with many attributes. Attribute values can be size,color,... . I am trying to create a custom search but I can't get the query to pull any product. $product_attributes = wc_get_attribute_taxonomies(); $attributes = array(); foreach ($product_attributes as $attribute) { $attribute_name = $attribute->attribute_name; $attribute_value = isset($params[$attribute_name]) ? $params[$attribute_name] : ''; if (!empty($attribute_value)) { $attributes['pa_' .$attribute_name] = $attribute_value; } } $ordering = WC()->query->get_catalog_ordering_args(); $ordering['orderby'] = array_shift(explode(' ', $ordering['orderby'])); $ordering['orderby'] = stristr($ordering['orderby'], 'price') ? 'meta_value_num' : $ordering['orderby']; dump($attributes); $args = array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids', 'stock_status' => 'instock', 'visibility' => 'visible', 'paginate' => true, 'orderby' => $ordering['orderby'], 'order' => 'DESC', 'attribute' => $attributes, ); $products = wc_get_products($args); what`s the problem
Jese Leos
September 1, 2024
Verified user
Thre issue is how the wc_get_products() function is used, the function doesn't directly support searching by attributes in the way you have structured it. To search for products based on custom attr you need to use tax_query within the args array Note: woocommerce attr are stored as custom taxonomies like ('pa_size', 'pa_color') Updated code $product_attributes = wc_get_attribute_taxonomies(); $tax_query = array('relation' => 'AND'); foreach ($product_attributes as $attribute) { $attribute_name = $attribute->attribute_name; $attribute_value = isset($params[$attribute_name]) ? $params[$attribute_name] : ''; if (!empty($attribute_value)) { $tax_query[] = array( 'taxonomy' => 'pa_' . $attribute_name, 'field' => 'slug', 'terms' => $attribute_value, ); } } $ordering = WC()->query->get_catalog_ordering_args(); $ordering['orderby'] = stristr($ordering['orderby'], 'price') ? 'meta_value_num' : $ordering['orderby']; $args = array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids', 'stock_status' => 'instock', 'visibility' => 'visible', 'paginate' => true, 'orderby' => $ordering['orderby'], 'order' => 'DESC', 'tax_query' => $tax_query, ); $products = wc_get_products($args); // Debug dump($products);