Retrieve products with specific attribute and in category – woocommerce

You should use wc_get_products and a custom filter for adding your specific query.

Example

I want to find products containing a specific attribute value “table-filter”.

  $args = array(
            'table-filter' => array(1,2,3)
        );
  $products = wc_get_products($args);

Than I have a filter for this:

add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2);

function my_handle_custom_query_var($query, $query_vars) {
    if (!empty($query_vars['table-filter'])) {
        $query['tax_query'][] = array(
            'taxonomy' => 'pa_table-filter',
            'field'    => 'term_id', //default
            'terms'    => $query_vars['table-filter'],
            'operator' => 'IN',
        );
    }
    return $query;
}

Hint: The generated attribute taxonomy from WooCommerce is always prefixed with “pa_”, so if you attributes slug is “table-filter”, the taxonomy will be “pa_table-filter”.

Leave a Comment