仅在WooCommerce结帐中为新用户添加验证电子邮件地址

时间:2018-07-23 16:00:55

标签: php wordpress woocommerce checkout email-validation

我想向WooCommerce结帐页面添加一个电子邮件地址验证字段,但仅适用于新用户。因此,如果用户已经登录,则不应要求他们输入验证电子邮件地址字段。

我已将此代码添加到我的functions.php中,并且效果很好。它要求输入电子邮件地址,但同时也为已经登录的用户使用。

add_filter( 'woocommerce_checkout_fields', 'bbloomer_add_email_verification_field_checkout' );

function bbloomer_add_email_verification_field_checkout( $fields ) {

    $fields['billing']['billing_email']['class'] = array('form-row-first');

    $fields['billing']['billing_em_ver'] = array(
        'label'     => __('Email Address Verification', 'bbloomer'),
        'required'  => true,
        'class'     => array('form-row-last'),
    'clear'     => true
    );

    return $fields;
}

// ---------------------------------
// 3) Generate error message if field values are different

add_action( 'woocommerce_checkout_process', 'bbloomer_matching_email_addresses' );
function bbloomer_matching_email_addresses() { 
    $email1 = $_POST['billing_email'];
    $email2 = $_POST['billing_em_ver'];
    if ( $email2 !== $email1 ) {
        wc_add_notice( __( 'Your email addresses do not match', 'bbloomer' ), 
 'error' );
    }
}

如何使该字段仅对未登录的用户显示?

1 个答案:

答案 0 :(得分:2)

我对您的代码进行了一些更改,并添加了必要条件,以使其仅适用于未登录的用户:

// Add or change Woocommerce Checkout fields
add_filter( 'woocommerce_checkout_fields', 'add_billing_email_check_field', 20, 1 );
function add_billing_email_check_field( $fields ) {
    // Only for non logged in users
    if( is_user_logged_in() ) return $fields;

    $fields['billing']['billing_email']['class'] = array('form-row-first');

    $fields['billing']['billing_email_check'] = array(
        'label'     => __('Email Address Verification', 'woocommerce'),
        'required'  => true,
        'class'     => array('form-row-last'),
        'clear'     => true
    );

    return $fields;
}

// Billing email validation check error message
add_action( 'woocommerce_checkout_process', 'billing_email_validation_check' );
function billing_email_validation_check() {
    if ( isset( $_POST['billing_email'] ) && isset( $_POST['billing_email_check'] ) &&
        $_POST['billing_email'] !== $_POST['billing_email_check'] )
        wc_add_notice( __( 'Your <strong>billing email address</strong> does not match.', 'woocommerce' ), 'error' );
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。