phpwordpresswoocommerceordersproduct-variations

WooCommerce get product variation attribute name and value from order items


I am making custom thank you page for my WooCommerce shop where I am able to display the Cart item's attribute and value correctly but in Thankyou page I failed to show that Can you please help me that ?

Working Code for mini cart item:

$items = WC()->cart->get_cart();
foreach($items as $item => $values) {
    
    $cart_item = WC()->cart->cart_contents[ $item ];
    $variations   = wc_get_formatted_cart_item_data( $cart_item );
    if( $cart_item['data']->is_type( 'variation' ) ){
        $attributes = $cart_item['data']->get_attributes();
        $variation_names = array();
        if( $attributes ){
            foreach ( $attributes as $key => $value) {
                $variation_key =  end(explode('-', $key));
                $variation_names[] = ucfirst($variation_key) .' : '. $value;
            }
        }
        echo implode( '<br>', $variation_names );
        
    }
    
}

And the output like

Color : Red
Size  : 4mm

Same thing I like to show in thank you page So I re-coded it like order format and loop through it which is not working

$items = $order->get_items();
foreach ($items as $item_key => $item) {
    $product = $item->get_product(); 
    if( $product->is_type( 'variation' )){
        $attributes = $product->get_variation_attributes();
        $variation_names = array();
        if( $attributes ){
            foreach ( $attributes as $key => $value) {
                $variation_key =  end(explode('_', $key));
                $variation_names[] = ucfirst($variation_key) .' : '. $value;
            }
        }
        echo implode( '<br>', $variation_names );
    }
}

Solution

  • Update (handling custom attributes too)

    Use $item->get_product() to get the current WC_Product Object from order items using get_attributes() method on product variations, instead of get_variation_attributes() which is to be used only on the parent variable products.

    $order_items = $order->get_items();
    
    foreach ($order_items as $item_key => $item) {
        $product = $item->get_product(); // Get the WC_Product Object
    
        if( $product->is_type( 'variation' ) ){
            $attributes = $product->get_attributes();
            $data_array = array();
    
            if( $attributes ){
                foreach ( $attributes as $meta_key => $meta ) {
                    $display_key   = wc_attribute_label( $meta_key, $product );
                    $display_value = $product->get_attribute($meta_key);
                    $data_array[]  = $display_key .' : '. $display_value;
                }
            }
            echo implode( '<br>', $data_array ) . '<br>';
        }
    }
    

    It should work now, for normal product attributes and custom ones too.