Reputation: 470
I'm trying to retrieve the product attributes of a WooCommerce product using this:
$m = get_post_meta($pid, '_product_attributes', false);
Where $pid is the ID of my product.
It partially works, but it doesn't return the value of the attributes. I have size and color set on the wp-admin...
[pa_size] => Array
(
[name] => pa_size
[value] =>
[position] => 0
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
[pa_color] => Array
(
[name] => pa_color
[value] =>
[position] => 1
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
Any idea?
Upvotes: 2
Views: 1115
Reputation: 253784
Since WooCommerce 3, you should better use WC_Product
method get_attributes()
as follow:
$product = wc_get_product( $pid ); // get an instance of the WC_Product Object
$attributes = $product->get_attributes(); // Get an array of WC_Product_Attribute Objects
// Loop through product WC_Product_Attribute objects
foreach ( $attributes as $name => $values ) {
$label_name = wc_attribute_label($values->get_name()); // Get product attribute label name
$data = $values->get_data(); // Unprotect attribute data in an array
$is_for_variation = $data['is_variation']; // Is it used for variation
$is_visible = $data['is_visible']; // Is it visible on product page
$is_taxonomy = $data['is_taxonomy']; // Is it a custom attribute or a taxonomy attribute
$option_values = array(); // Initializing
// For taxonomy product attribute values
if( $is_taxonomy ) {
$terms = $values->get_terms(); // Get attribute WP_Terms
// Loop through attribute WP_Term
foreach ( $terms as $term ) {
$term_name = $term->name; // get the term name
$option_values[] = $term_name;
}
}
// For "custom" product attributes values
else {
// Loop through attribute option values
foreach ( $values->get_options() as $term_name ) {
$option_values[] = $term_name;
}
}
// Output for testing
echo '<strong>' . $label_name . '</strong>:
<ul><li>' . implode('</li><li>', $option_values) . '</li><br>';
}
Tested and works.
Upvotes: 2