Search code examples
phpwordpresswoocommerceprotectedorders

Access and display order item meta data in Woocommerce


In Woocommerce I am trying to display the results of order item object and to access it:

$product_meta = $item->get_meta_data();
print_r ($product_meta);

This is what I am trying to pull:

enter image description here

EDIT: This is the output that I get using $item->get_formatted_meta_data( '', true ):

enter image description here


Solution

  • To get all order item meta data, you will use WC_Order_Item get_formatted_meta_data() method with specific arguments, this way:

    // Accessible non protected Order item meta data
    $item_meta_data = $item->get_formatted_meta_data( '', true );
    
    // Formatted raw Output
    echo '<pre>'; print_r($item_meta_data); echo '</pre>';
    

    To access some order item properties, you can use any WC_Order_Item_Product method like:

    $item->get_product(); // Get the WC_Product object
    
    $item->get_product_id(); // Get the Product ID
    
    $item->get_variation_id(); // Get the Variation ID
    
    $item->get_name(); // Get the Product name
    
    $item->get_quantity(); // Get the item quantity 
    
    // and so on …
    

    Then if you need to access a specific "custom" order item data value, you will use WC_Data get_meta() method:

    $custom_value = $item->get_meta("_custom_key");
    

    See: Get Order items and WC_Order_Item_Product in Woocommerce 3


    Update (displaying your required custom order item meta data)

    The data you need can be accessed and displayed this way:

    if( $lessons = $item->get_meta('lessons') ) {
        echo '<p>Lessons: '.$lessons.'</p>';
    }
    
    if( $tour_guide = $item->get_meta('tour guide') ) {
        echo '<p>Tour Guide: '.$tour_guide.'</p>';
    }
    

    I hope that this works now.