Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

woocommerce get attribute terms

Tags:

In Woocommerce you can add global product attributes and terms. So for instance:

Size (attribute) small  (term) medium (term) large  (term) 

This is product independent. You can then select from the pre defined attributes on a product.

I need to get all of the terms in an attribute with php. So select the attribute required, eg size, and then return an array including [small,medium,large].

Seems simple enough but I can't find any help on doing this.

like image 510
phantomdentist Avatar asked May 01 '13 17:05

phantomdentist


People also ask

How do I get product attributes in WooCommerce?

You can use: global $product; echo wc_display_product_attributes( $product ); To customise the output, copy plugins/woocommerce/templates/single-product/product-attributes. php to themes/theme-child/woocommerce/single-product/product-attributes.

How do I use attributes in WooCommerce?

Go to: Products > Add Product (or edit an existing one). Select the Attributes tab in the Product Data. There you can choose any of the attributes that you've created in the dropdown menu. Select Add.


2 Answers

Slightly confusing, especially when looking through the WooCommerce Docs since there is absolutely no mention of getting a list of the terms/attributes.

The Attributes are saved as a custom taxonomy, and the terms are taxonomy terms. That means you can use native Wordpress functions: Wordpress get_terms() Function Reference

By clicking on an attribute in WooCommerce, you can look in the URL and you can see they are all prepended with 'pa_'

This is likely what you need:

$terms = get_terms("pa_size"); foreach ( $terms as $term ) { echo "<option>" . $term->name . "</option>"; } 
like image 146
Mike Szostech Avatar answered Sep 19 '22 14:09

Mike Szostech


I wanted to be able to get all the different attributes from the backend that were set, and get them in an array for me to work with, I took some code from the class-wc-admin-attributes.php file and modified it for my needs:

<?php  $attribute_taxonomies = wc_get_attribute_taxonomies(); $taxonomy_terms = array();  if ($attribute_taxonomies) :     foreach ($attribute_taxonomies as $tax) :         if (taxonomy_exists(wc_attribute_taxonomy_name($tax->attribute_name))) :             $taxonomy_terms[$tax->attribute_name] = get_terms(wc_attribute_taxonomy_name($tax->attribute_name), 'orderby=name&hide_empty=0');         endif;     endforeach; endif;  var_dump($taxonomy_terms);  exit; 

This will loop through all the attribute taxonomies, retrieve the terms for each, leaving you with an array of term objects to work with for each taxonomy.

like image 28
Nick Avatar answered Sep 20 '22 14:09

Nick