手动将产品添加到 WooCommerce 管理订单时,将产品自定义元数据保存为订单项元数据

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

我试图在从管理员向订单添加产品时将自定义产品元添加到订单项元。这是我的代码,它在后端什么都不做...

// Order items: Save product "location" as order item meta data
add_action( 'woocommerce_ajax_add_order_item_meta', 'action_before_save_order_item_callback' );
function action_before_save_order_item_callback($item, $cart_item_key, $values, $order) {
    if ( $location = $values['data']->get_meta('location') ) {
        $item->update_meta_data( 'location', $location ); // Save as order item meta
    }
}

您没有使用正确的函数挂钩参数 $item_id$item$order,并且没有使用正确的方法。请尝试以下 (代码已注释):

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

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。