在Woocommerce中启用自定义结帐电子邮件字段验证

时间:2018-10-27 16:56:44

标签: php wordpress validation woocommerce checkout

我通过以下代码在WooCommerce Checkout上添加了自定义电子邮件字段

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'));

它可以正常工作,所需的验证也可以,但是当输入的电子邮件地址无效时它不会出错。

我想知道是否有内置的WooCommerce方法可以实现与帐单电子邮件相同的功能?

谢谢!

1 个答案:

答案 0 :(得分:0)

  

您应该始终在问题中提供完整的功能代码以及所有相关代码。

我已将giftcard-friend-email更改为 _giftcard_friend_email ,因为它会保存为订单元数据,因此下划线是更好的选择。

以下代码将:

  • 在结帐页面上显示自定义电子邮件字段(因此删除您的代码)。
  • 将验证此电子邮件字段是否为空,以及是否为有效电子邮件。
  • 下订单时将此自定义电子邮件值另存为订单元数据

代码:

// 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'] ) );
    }
}

代码进入活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。