Get a custom field value saved in Order items meta in a hooked function

孤街浪徒 提交于 2020-01-14 05:09:09

问题


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))



来源:https://stackoverflow.com/questions/44985868/get-a-custom-field-value-saved-in-order-items-meta-in-a-hooked-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!