For a specific user role I want to add a specific customer note to the order.
This is my code:
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();
}
}
But this puts the message in the wrong place. When you check an order in the backend it's been displayed in the purple message boxes.
I want the message to be displayed as a customer note which is displayed under the shipping address. Because my API is picking up the notes from that place and puts them in our ERP.
I tried to change
$order->add_order_note( $note );
to
$order->add_order_note( $note, 'is_customer_note', true );
But without the desired result, any advice?
CodePudding user response:
To display the message as a customer note displayed below the shipping address, you can use set_customer_note() instead.
So you get:
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 );
To keep the original message (when NOT empty) use this instead:
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 );