1
votes

I added custom email field on WooCommerce Checkout by following code

woocommerce_form_field('giftcard-friend-email', array(
'type'        => 'email',
'class'       => array( 'form-row-wide' ),
'required'    => true,
'label'       => __('To: Friend Email') ,
'placeholder' => __('Friend Email') ,
),
$checkout->get_value('giftcard-friend-email'));

It's working, required validation also working but it doesn't give error when input is an invalid email address.

I wonder if there's any built-in WooCommerce method to achieve this same as Billing Email?

Thanks!

1

1 Answers

1
votes

You should always provide in your question the full function code and all related code too.

I have changed the giftcard-friend-email to _giftcard_friend_email a more normal slug as it will be saved as order meta data, so underscores are better option.

The following code will:

  • Display a custom email field in checkout page (so remove your code).
  • Will validate this email field checking that is not empty and a valid email.
  • Save this custom email value as order meta data when order is placed

The code:

// Display the custom checkout field
add_action('woocommerce_before_order_notes', 'add_custom_checkout_field', 20, 1 );
function add_custom_checkout_field( $checkout ) {

    echo '<div id="friend_email_checkout_field">';

    woocommerce_form_field( '_giftcard_friend_email', array(
        'type'        => 'email',
        'label'       => __('To: Friend Email') ,
        'placeholder' => __('Friend Email') ,
        'class'       => array( 'form-row-wide' ),
        'required'    => true,
    ), $checkout->get_value('_friend_email') );

    echo '</div>';
}

// Field custom email Validation
add_action( 'woocommerce_checkout_process', 'friend_email_checkout_field_validation' );
function friend_email_checkout_field_validation() {
    if( isset($_POST['_giftcard_friend_email']) && empty($_POST['_giftcard_friend_email']) )
        wc_add_notice( __( 'Please fill in the "Friend Email" field.', 'woocommerce' ), 'error' );
    elseif( !preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $_POST['_giftcard_friend_email'] ) ){
        wc_add_notice( __( 'Please enter a valid "Friend Email".', 'woocommerce' ), 'error' );
    }
}

// Save the checkout field value to order meta data
add_action('woocommerce_checkout_create_order', 'save_friend_email_checkout_field_value', 20, 2 );
function save_friend_email_checkout_field_value( $order, $data ) {
    if ( isset( $_POST['_giftcard_friend_email'] ) ) {
        $order->update_meta_data( '_giftcard_friend_email', sanitize_email( $_POST['_giftcard_friend_email'] ) );
    }
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.