Search code examples
phpwordpresswoocommercemetadataorders

Retrieve custom order item meta data values in Woocommerce 3


I have the following code which is creating cart Item data based on some custom fields:

function parcel_add_shipment_text_to_cart_item( $cart_item_data, $product_id, $variation_id ) { 

$service = filter_input( INPUT_POST, 'servicelevel' );
$servicecode = filter_input( INPUT_POST, 'servicecode'); 
$price = filter_input( INPUT_POST, 'sellprice' );
$chargeweight = filter_input( INPUT_POST, 'chargeweight' );  

$cart_item_data['servicelevel'] = $service;
$cart_item_data['servicecode'] = $servicecode;
$cart_item_data['serviceprice'] = $price;
$cart_item_data['chargeweight'] = $chargeweight;

return $cart_item_data; }


add_filter( 'woocommerce_add_cart_item_data', 'parcel_add_shipment_text_to_cart_item', 10, 3 );

Then I add the cart meta here:

function add_custom_field_text_to_order_items( $item, $cart_item_key, $values, $order ) {


$item->add_meta_data( __( 'Service Level', 'Shipment' ), $values['servicelevel'] );
$item->add_meta_data( __( 'Your Reference', 'Shipment' ), $values['shipmentref'] );
$item->add_meta_data( __( 'Sell Price', 'Shipment' ), $values['serviceprice'] );
$item->add_meta_data( __( 'Charge Weight', 'Shipment' ), , $values['chargeweight'] );  } 

add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_field_text_to_order_items', 10, 4 );  

How do I retrieve the above Item meta data to be used in the woocommerce_payment_complete or order complete screen? I know the above data is working as I can see it on the order screen and email. Your help would be much appreciated.


Solution

  • Using your custom order item meta data in woocommerce_payment_complete action hook (or in any other hook where you can get the order ID or the order object):

    add_action( 'woocommerce_payment_complete', 'on_action_payment_complete', 10, 1 );
    function on_action_payment_complete( $order_id ) {
        // Get an instance of the WC_Order Object
        $order = wc_get_order( $order_id );
    
        // Loop through order items
        foreach( $order->get_items() as $item_id => $item ){
            $servicelevel = $item->get_meta('Service Level');
            $servicecode  = $item->get_meta('Your Reference');
            $serviceprice = $item->get_meta('Sell Price');
            $chargeweight = $item->get_meta('Charge Weight');
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works. The code inside the hook is tested and really works.