vladkrasovsky
10/26/2016 - 1:28 PM

WooCommerce Add confirm email option at checkout (goes in functions.php)

WooCommerce Add confirm email option at checkout (goes in functions.php)

<?php
add_filter( 'woocommerce_checkout_fields' ,'add_checkout_field' );
add_filter( 'default_checkout_billing_email-2', 'default_field_value' , 10, 2 );
add_filter( 'woocommerce_process_checkout_field_billing_email-2' ,  'validate_email_address'  );

function add_checkout_field( $fields = array() ) {

  $fields['billing']['billing_email-2'] = array(
    'label' 			=> __( 'Confirm Email Address', 'wc_emailvalidation' ),
    'placeholder' 		=> _x( 'Email Address', 'placeholder', 'wc_emailvalidation' ),
    'required' 			=> true,
    'class' 			=> apply_filters( 'woocommerce_confirm_email_field_class', array( 'form-row-first' ) ),
    'clear'				=> true,
    'validate'			=> array( 'email' ),
  );

  return $fields;

}

function default_field_value( $value = null, $field = 'billing_email-2' ) {
  if ( is_user_logged_in() ) {
    global $current_user;
    $value = $current_user->user_email;
  }
  return $value;
}

function validate_email_address( $confirm_email = '' ) {
  global $woocommerce;

  $billing_email = $woocommerce->checkout->posted['billing_email'];

  if( strtolower( $confirm_email ) != strtolower( $billing_email ) ) {

    $notice = sprintf( __( '%1$sEmail addresses%2$s do not match.' , 'wc_emailvalidation' ) , '' , '' );

    if ( version_compare( WC_VERSION, '2.3', '<' ) ) {
      $woocommerce->add_error( $notice );
    } else {
      wc_add_notice( $notice, 'error' );
    }

  }

  return $confirm_email;
}