Product attribute empty value from order item in Woocommerce 3

Multi tool use
Product attribute empty value from order item in Woocommerce 3
I know that there are a lot of questions already for that matter but im not able to figure out how to get a custom product attribute from an woocommerce order. here is what i have try:
$order = wc_get_order( $order_id );
$order_data = $order->get_data();
foreach ($order->get_items() as $item_key => $item_values) {
$product = $item_values->get_product(); // Get the product
$product_id = $item_values->get_product_id(); // the Product id
$tokens = get_post_meta($product_id, 'Tokens', true);
}
I have also try:
$tokens = $product->get_attribute( 'Tokens' );
and
$tokens = array_shift( wc_get_product_terms( $product_id, 'Tokens', array( 'fields' => 'names' ) ) );
My custom product attribute has the name "Tokens" and the value 5000 but im getting an empty return,
what am i doing wrong?
@LoicTheAztecso what i have to do?
– CDrosos
Jun 30 at 10:04
1 Answer
1
That can happen for a variable product when the product attribute is not set as an attribute for variations.
So when you have a product variation as order item, you need to get the parent variable product to get your product attribute value (if this product attribute is not set as an attribute for variations).
If it is the case for "Tokens" product attribute, try the following:
$attribute = 'Tokens';
$order = wc_get_order( 857 );
// Loop through order line items
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product(); // Get the WC_Product object
// For Product Variation type
if( $item->get_variation_id() > 0 ){
$parent = wc_get_product($product->get_parent_id());
$term_names = $parent->get_attribute($attribute);
}
// For other Product types
else {
$term_names = $product->get_attribute($attribute);
}
// Testing display (the string of coma separated term names if many)
if( ! empty( $term_name ) )
echo '<p>'.$term_name.'</p>';
}
Tested and works in Woocommerce 3+
works amazing, thanks
– CDrosos
Jul 1 at 8:49
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That can happen for a variable product when the product attribute is not set as an attribute for variations. When you have a product variation from this parent variable product as order item, you can't get the anything from the product variation itself and you need to get the parent variable product, to get your product attribute value.
– LoicTheAztec
Jun 30 at 1:03