在 WooCommerce 中为特定用户角色添加关于订单创建的额外客户注释

Add extra customer note on order creation for specific user role in WooCommerce

对于特定的用户角色,我想在订单中添加特定的客户备注。

这是我的代码:

add_action( 'woocommerce_new_order', 'add_customer_note_user_role' );
function add_customer_note_user_role( $order_id ) {

    $user_info = get_userdata(get_current_user_id());

    if ( $user_info->roles[0]=="administrator" ) {

        $order = wc_get_order( $order_id );

        // The text for the note
        $note = 'This is the message';

        // Add the note
        $order->add_order_note( $note );

        // Save the data
        $order->save();
    }
}

但这会将消息放在错误的位置。当您在后台查看订单时,它会显示在紫色消息框中。

我希望消息显示为客户备注,显示在送货地址下方。因为我的 API 正在从那个地方提取笔记并将它们放入我们的 ERP。

我试着改变

$order->add_order_note( $note );

$order->add_order_note( $note, 'is_customer_note', true );

但是没有得到想要的结果,有什么建议吗?

要将消息显示为送货地址下方的客户备注,您可以改用 set_customer_note()

所以你得到:

function action_woocommerce_new_order( $order_id ) {
    // Get the WC_Order Object
    $order = wc_get_order( $order_id );

    // Get the WP_User Object
    $user = $order->get_user();
    
    // Check for "administrator" user roles only
    if ( is_a( $user, 'WP_User' ) && in_array( 'administrator', (array) $user->roles ) ) {
        // The text for the note
        $note = 'This is the message';
        
        // Set note
        $order->set_customer_note( $note );
        
        // Save
        $order->save();
    }
}
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );

要保留原始消息(当不为空时),请改用此消息:

function action_woocommerce_new_order( $order_id ) {
    // Get the WC_Order Object
    $order = wc_get_order( $order_id );

    // Get the WP_User Object
    $user = $order->get_user();
    
    // Check for "administrator" user roles only
    if ( is_a( $user, 'WP_User' ) && in_array( 'administrator', (array) $user->roles ) ) {
        // The text for the note
        $note = 'This is the message';
        
        // Get customer note
        $customer_note = $order->get_customer_note();
        
        // NOT empty
        if ( ! empty ( $customer_note ) ) {
            $note = $customer_note . ' | ' . $note;
        }
        
        // Set note
        $order->set_customer_note( $note );
        
        // Save
        $order->save();
    }
}
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );