2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.