2
votes

I have a custom product type and custom loop for listing woocommerce products

$query_args = array(
 'post_type' => 'product',
 'tax_query' => array(
      array(
          'taxonomy' => 'product_type',
          'field'    => 'slug',
          'terms'    => 'custom_type', 
      ),
  ),
);

$r = new WP_Query( $query_args );

if ( $r->have_posts() ) {

I have custom data attributes in product datas. How can I use them in loop? How can I filter products with this attributes?

For example I have color and size data attributes. Now how can I the list red and large products?

1
I believe you are trying to ask "how do I query products by their custom attributes?" If so, my answer below should do it.helgatheviking

1 Answers

3
votes

Attributes are just custom taxonomies. Keep in mind that the taxonomy name will always be the attribute name preceded by pa_. This is just WooCommerce's naming convention to avoid conflicting taxonomy names. To query more than one taxonomy, see the "Multiple Taxonomy Handling" section in WP Query Parameters.

If, for example, you were trying to query products of product type = custom_type and color = red and a size attribute = large, your example args would look like this:

$query_args = array(
 'post_type' => 'product',
 'tax_query' => array(
      array(
          'taxonomy' => 'product_type',
          'field'    => 'slug',
          'terms'    => 'custom_type', 
      ),
      array(
          'taxonomy' => 'pa_color',
          'field'    => 'slug',
          'terms'    => 'red', 
      ),
      array(
          'taxonomy' => 'pa_size',
          'field'    => 'slug',
          'terms'    => 'large', 
      ),
  ),
);