Search code examples
wordpresswoocommercehook-woocommerce

How to update billing_email in Woocommerce (if empty)


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', 'example@example.com' );
    }
}

Solution

  • 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 a WC_Order instance and an order ID, respectively.

    Option 1: Use woocommerce_checkout_create_order

    add_action( 'woocommerce_checkout_create_order', 'set_email_for_guest', 10, 2 );
    function set_email_for_guest( $order, $data ) { // first param is a WC_Order instance
        if ( empty( $data['billing_email'] ) ) {
            $order->update_meta_data( '_billing_email', 'foo@example.com' );
        }
    }
    

    Option 2: Use woocommerce_checkout_update_order_meta

    add_action( 'woocommerce_checkout_update_order_meta', 'set_email_for_guest', 10, 2 );
    function set_email_for_guest( $order_id, $data ) { // first param is an order/post ID
        if ( empty( $data['billing_email'] ) ) {
            update_post_meta( $order_id, '_billing_email', 'foo@example.com' );
        }
    }
    

    So just choose whichever hook you prefer, but the first one above runs first.