[php] 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.

This question is related to php wordpress woocommerce product custom-taxonomy

The answer is


The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:

$array=get_post_meta($product->id);

key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta


Try this to get an array of attribute name => attribute value(s):

global $product;

$formatted_attributes = array();

$attributes = $product->get_attributes();

foreach($attributes as $attr=>$attr_deets){

    $attribute_label = wc_attribute_label($attr);

    if ( isset( $attributes[ $attr ] ) || isset( $attributes[ 'pa_' . $attr ] ) ) {

        $attribute = isset( $attributes[ $attr ] ) ? $attributes[ $attr ] : $attributes[ 'pa_' . $attr ];

        if ( $attribute['is_taxonomy'] ) {

            $formatted_attributes[$attribute_label] = implode( ', ', wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ) );

        } else {

            $formatted_attributes[$attribute_label] = $attribute['value'];
        }

    }
}

//print_r($formatted_attributes);

return $formatted_attributes;

It's little inefficient but does the trick.


woocommerce_get_product_terms() is now deprecated.

Use wc_get_product_terms() instead.

Example:

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

You can get the single value for the attribute with below code:

$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);

Although @airdrumz solutions works, you will get lots of errors about you doing it wrong by accessing ID directly, this is not good for future compatibility.

But it lead me to inspect the object and create this OOP approach:

function myplug_get_prod_attrs() {
    // Enqueue scripts happens very early, global $product has not been created yet, neither has the post/loop
    global $product;
    $wc_attr_objs = $product->get_attributes();
    $prod_attrs = [];
    foreach ($wc_attr_objs as $wc_attr => $wc_term_objs) {
        $prod_attrs[$wc_attr] = [];
        $wc_terms = $wc_term_objs->get_terms();
        foreach ($wc_terms as $wc_term) {
            array_push($prod_attrs[$wc_attr], $wc_term->slug);
        }
    }
    return $prod_attrs;
}

Bonus, if you are performing the above early before the global $product item is created (e.g. during enqueue scripts), you can make it yourself with:

    $product = wc_get_product(get_queried_object_id());

Most updated:

$product->get_attribute( 'your_attr' );

You will need to define $product if it's not on the page.


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.


Use below code to get all attributes with details

    global $wpdb;

    $attribute_taxonomies = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );
    set_transient( 'wc_attribute_taxonomies', $attribute_taxonomies );

    $attribute_taxonomies = array_filter( $attribute_taxonomies  ) ;

    prin_r($attribute_taxonomies);

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to wordpress

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ How to get WooCommerce order details Wordpress plugin install: Could not create directory WooCommerce: Finding the products in database How to get post slug from post in WordPress? How to get featured image of a product in woocommerce Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610 Use .htaccess to redirect HTTP to HTTPs Load More Posts Ajax Button in WordPress How to decode encrypted wordpress admin password?

Examples related to woocommerce

How to get WooCommerce order details WooCommerce: Finding the products in database How to get featured image of a product in woocommerce How to display Woocommerce product price by ID number on a custom page? Get cart item name, quantity all details woocommerce Woocommerce, get current product id How to modify WooCommerce cart, checkout pages (main theme portion) How can I get customer details from an order in WooCommerce? How can I get the order ID in WooCommerce? Woocommerce get products

Examples related to product

How to get WooCommerce order details WooCommerce: Finding the products in database How to display Woocommerce product price by ID number on a custom page? Woocommerce, get current product id Get custom product attributes in Woocommerce Magento Product Attribute Get Value What's the function like sum() but for multiplication? product()?

Examples related to custom-taxonomy

Get custom product attributes in Woocommerce