Email address not mandatory on our checkout page.
We want to update billing_email
to our custom email if the customer does not provide an email.
Here is my code:
add_action('woocommerce_thankyou', 'set_email_for_guest');
function set_email_for_guest( $order_id ) {
$email = get_post_meta( $order_id, 'billing_email', true );
if(empty($email)){
update_post_meta( $order_id, '_billing_email', '[email protected]' );
}
}
3
Answers
You have an error in the meta key:
You want to update
billing_email
to custom email if the user does not provide a billing email on checkout.So it would be a possible solution to the problem to give the email field on your checkout page a default value. This default value can be the customer email if logged in, or as in your example a hard coded value. This way you will always have a value in this field.
Addition:
If you want to make it read only, so the user can not edit the default value, you can set this in the fields custom attributes.
I believe the hook that you should use is not
woocommerce_thankyou
. Instead, you should choose from one of the following hooks which both worked for me in WordPress 5.6.1 with WooCommerce 5.0.0 (which are both the latest releases as of writing):And note that these hooks pass
$data
as the second parameter which is an array of the POST-ed/submitted (and processed) form data. However, the first parameter is aWC_Order
instance and an order ID, respectively.Option 1: Use
woocommerce_checkout_create_order
Option 2: Use
woocommerce_checkout_update_order_meta
So just choose whichever hook you prefer, but the first one above runs first.