I want to add a default order comment (or pre populate the order_comments
field) if the cart total is over 25 euros.
I already found this post about it: Add a custom order note programmatically in Woocommerce admin order edit pages
I almost got it working:
add_filter( 'woocommerce_checkout_fields' , 'set_default_order_comment' );
function set_default_order_comment( $order, $fields ) {
// Targeting My account section
if ( $order->get_total() > 25 ) {
$fields['order']['order_comments']['default'] = 'Custom note!!';
}
return $fields;
}
At least, I think this should be it, but not quite right yet. I got this error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function
How can create a simple function that checks the total amount in cart and if it is over 25 euro automaticly add an default order comment to the order?
CodePudding user response:
It can be done like this.
/**
* Add a custom note when the order total is above 25.
*
* @param int $order_id Order ID.
* @param WC_Order $order Order object.
*/
function vkh_woocommerce_new_order_action( $order_id, $order ) {
if ( $order->get_total() > 25 ) {
$note = __( 'Write your note here!' );
// Add the note
$order->add_order_note( $note );
}
}
add_action( 'woocommerce_new_order', 'vkh_woocommerce_new_order_action', 10, 2 );
CodePudding user response:
The error is there because $order
is not an argument of the woocommerce_checkout_fields
filter hook, you should use get_cart_contents_total()
instead
So you get:
function filter_woocommerce_checkout_fields( $fields ) {
// Get cart total
$cart_total = WC()->cart->get_cart_contents_total();
// Greater than
if ( $cart_total > 25 ) {
$fields['order']['order_comments']['default'] = __( 'Custom note!', 'woocommerce' );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'filter_woocommerce_checkout_fields', 10, 1 );