我正在尝试添加自定义字段jckwds_date
作为订单备注。我一生都无法弄清楚为什么这段代码在 functions.php
中不起作用?
代码还只允许在特定角色类型中添加注释。
function wdm_my_custom_notes_on_single_order_page($order){
$user = wp_get_current_user();
$allowed_roles = array('eu_no_vat', 'super_wholesale_customer', 'wholesale_customer');
if( array_intersect($allowed_roles, $user->roles ) ) {
$value = get_post_meta( $product->get_id(), 'jckwds_date', true );
echo $value;
$order->add_order_note( $value, $is_customer_note = 1 );
}
}
基本上我需要THIS :
待添加HERE :
最佳答案
更新:
以下代码将从订单自定义字段“jckwds_date”(或结帐发布字段值“jckwds_date”)添加订单注释,该注释将显示在后端中定义的用户角色:
add_action( 'woocommerce_checkout_update_order_meta', 'product_custom_field_to_custom_order_notes', 100, 2 );
function product_custom_field_to_custom_order_notes( $order_id, $data ){
// HERE define allowed user roles
$allowed_roles = array('administrator', 'super_wholesale_customer', 'wholesale_customer');
$user_id = get_post_meta( '_customer_user', 'jckwds_date', true );
$user = new WP_User( $user_id );
// Exit if no matched user roles
if( ! array_intersect( $allowed_roles, $user->roles ) ) return;
// Get the date custom field (or checkout field)
if( get_post_meta( $order_id, 'jckwds_date', true ) ){
$note = get_post_meta( $order_id, 'jckwds_date', true );
} elseif( isset( $_POST['jckwds_date'] ) ){
$note = sanitize_text_field( $_POST['jckwds_date'] );
}
// The order note
if( isset($note) && ! empty($note) ){
$order = wc_get_order( $order_id ); // The WC_Order Object
$order->add_order_note( $note ); // Add the note
$order->save(); // Save the order
}
}
代码位于事件子主题(或事件主题)的 function.php 文件中。它应该可以工作。
关于php - 在 Woocommerce 中添加自定义字段作为订单备注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494501/