Save product custom meta as order item meta when manually adding products to WooCommerce admin orders

You are not using the right function hook arguments which are $item_id, $item, $order and not using the right way. Try the following instead (code is commented):

add_action( 'woocommerce_ajax_add_order_item_meta', 'action_before_save_order_item_callback', 9999, 3 );
function action_before_save_order_item_callback( $item_id, $item, $order ) {
    $product  = $item->get_product(); // Get the WC_Product Object
    $location = $product->get_meta('location'); // Get custom meta data

    // If custom field is empty on a product variation check on the parent variable product
    if( empty($location) && $item->get_variation_id() > 0 ) {
        $parent_product = wc_get_product( $item->get_product_id() ); // Get parent WC_Product Object
        $location = $product->get_meta('location'); // Get custom meta data
    }

    // If product meta data exist
    if( ! empty($location) ) {
        $item->update_meta_data( 'location', $location ); // Set it as order item meta
        $item->save(); // save it
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top