Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom product attributes in Woocommerce

In Woocommerce, I am trying to get product custom attribute values but I fail miserably and I don't get anything.

So I tried:

global $woocommerce, $post, $product; $res = get_post_meta($product->id); print_r(unserialize($res['_product_attributes'][0])); 

And I'm getting this raw data:

[pa_koostis] => Array         (             [name] => pa_koostis             [value] =>              [position] => 0             [is_visible] => 1             [is_variation] => 0             [is_taxonomy] => 1         ) 

I know that there is a value because it is shown in the attribute section, but I just can't find a way to get it displayed with my custom code.

like image 825
Nick Avatar asked Nov 14 '12 07:11

Nick


People also ask

How do I add a custom product attribute 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.

Where are WooCommerce product attributes stored?

Product attributes are stored in two locations - in wp_terms, wp_term_taxonomy and wp_term_relationships (that's the first place - each attribute is preceded by pa_ for its taxonomy name - e.g. if you have a color attribute, it's under pa_color) then also as a PHP serialized array in wp_postmeta under '_ ...

How do I get variation attributes in WooCommerce?

You can select variable product from the product data meta box dropdown. Add attributes and values to the product. Here, you can also check the options to display the attributes on the product page and make it available for creating variations. One done, click the Save attributes button.


2 Answers

Edited: The woocommerce_get_product_terms is deprecated since Woocommerce version 3

Go with the following as @datafeedr wrote in his answer:

global $product; $koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) ); 

or even more compact:

global $product; $koostis = $product->get_attribute( 'pa_koostis' ); 

Original answer:

$result = array_shift(woocommerce_get_product_terms($product->id, 'pa_koostis', 'names')); 
like image 122
Nick Avatar answered Sep 19 '22 20:09

Nick


Update for 2018. 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.php and modify that.

like image 29
david_nash Avatar answered Sep 17 '22 20:09

david_nash