从管理员向订单中添加产品时,我正在尝试将自定义产品元添加到订单商品中。这是我的代码,在后端不执行任何操作...
// 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
}
}
答案 0 :(得分:1)
您没有使用正确的函数挂钩参数$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文件中。经过测试,可以正常工作。