Get custom product attributes in Woocommerce
To retrieve custom product attributes in WooCommerce, you can use the get_post_meta() function.
To retrieve product attributes in WooCommerce, you can use the wc_get_product() function combined with the get_meta() method. This approach is recommended for WooCommerce 3.0+ as it properly handles the platform's data structure.
Here is an example of how to retrieve a taxonomy-based attribute (e.g., Color, Size) for a product:
How to retrieve product attributes in WooCommerce?
<?php
$product_id = 123;
$product = wc_get_product( $product_id );
$custom_attribute = '';
if ( $product ) {
$custom_attribute = $product->get_meta( 'attribute_pa_custom_attribute', true );
}In this example, $product_id is the ID of the product. The meta key 'attribute_pa_custom_attribute' uses the attribute_pa_ prefix followed by the attribute slug. This prefix is specific to taxonomy-based attributes created in WooCommerce's "Attributes" settings. The third argument, true, ensures the function returns a single value instead of an array.
You can then use the $custom_attribute variable to access the retrieved value.
Note on custom product attributes: Attributes added via the "Custom product attributes" tab on the product edit screen are stored in the product_attributes meta key as a serialized PHP array. The get_meta() function automatically unserializes it when the third argument is true, so no manual decoding is needed:
$custom_attrs = $product->get_meta( 'product_attributes', true );You can then access or iterate through the retrieved attributes:
if ( is_array( $custom_attrs ) ) {
foreach ( $custom_attrs as $slug => $data ) {
echo $slug . ': ' . $data['value'] . '<br>';
}
}