Search code examples
phpwordpresswoocommerceordersproduct-variations

Get a product attribute value when not set for variations from WooCommerce order items


I have variable products with variations (gift voucher in that case). In those variable products I have also an attribute not set for variations, that is an internal reference which should not be displayed to the customer (a code number related to accounting in this case).

How can I retrieve this attribute value from WooCommerce order items, no matter what variation the customer has ordered?

Right now, I'm trying to retrieve this attribute value using the following code:

foreach($wcOrder->get_items() as $item) 
{
    $wcProduct = $item->get_product();

    if (is_object($wcProduct))
    {
        if (key_exists(MY_INTERNAL_ATTRIBUTE_NAME, $wcProduct->get_attributes())) {
            $attributeValue = $wcProduct->get_attribute( PROPERTY_TYPE_B2B_ARTICLE ));
            ...
        }
    }
}

It works when the order item is a simple product, But I'm not getting any attribute value when the order item is a product variation.

How can I get an attribute value when it's not set for variations, from WooCommerce order items?


Solution

  • For product attributes set on the variable product not used for variations, you need to get the parent variable product, when the order item is a product variation.

    Try the following revisited code:

    foreach($wcOrder->get_items() as $item) 
    {
        $product = $item->get_product();
    
        if ( $item->get_variation_id() > 0 ) {
            $wcProduct = wc_get_product( $item->get_product_id() )
        } else {
            $wcProduct = $item->get_product();
        }
            
        if ( key_exists( MY_INTERNAL_ATTRIBUTE_NAME, $wcProduct->get_attributes() ) ) {
            $attributeValue = $product->get_attribute( PROPERTY_TYPE_B2B_ARTICLE );
            // ...
        }
    }
    

    It should work