Get a custom field value saved in Order items meta

2019-06-01 08:51发布

问题:

I am able to add, validate, display on cart and checkout page a custom field on the Product Page.Please can someone tell me how can I retrieve the custom field values using woocommerce_order_status_completed hook?

I want to send an additional email including the custom field data after the confirmation email is sent to the user

static function sendCustomData($order_id) {
    $order = wc_get_order($order_id);
    $items = $order->get_items();

    foreach ($items as $item) {
        $product_id = $item['product_id'];

        $Id = get_post_meta($product_id, '_wpws_ID', true);
        $first_name = $order->get_billing_first_name();
        $billing_email = $order->get_billing_email();


        if (empty($Id))
        continue;

        $mail = new CustomMails();
        $mail->SendMailtoReaderOnWCOrderComplete($first_name, $billing_email, $Id);
    }
}
add_action('woocommerce_order_status_completed','sendCustomData');

Saving custom order meta value

public static function tshirt_order_meta_handler( $item_id, $values, $cart_item_key ) {
    if( isset( $values['name_on_tshirt'] ) ) {
        wc_add_order_item_meta( $item_id, "name_on_tshirt", $values['name_on_tshirt'] );
    }
}
add_action( 'woocommerce_new_order_item', 'tshirt_order_meta_handler', 1, 3 );

回答1:

To get "name_on_tshirt" custom field, you need to get the order Item ID and you need to use wc_get_order_item_meta() function this way:

foreach ($order->get_items() as $item_id => $item) {
    ## HERE ==> Get your custom field value
    $name_on_tshirt wc_get_order_item_meta( $item_id, "name_on_tshirt", true );
}


回答2:

change if (empty($Id)) .. to if (empty($wbnId))