【问题标题】:Enable custom checkout email field validation in Woocommerce在 Woocommerce 中启用自定义结帐电子邮件字段验证
【发布时间】:2019-04-01 03:08:18
【问题描述】:

我通过以下代码在 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 方法可以实现与账单电子邮件相同的功能?

谢谢!

【问题讨论】:

    标签: php wordpress validation woocommerce checkout


    【解决方案1】:

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

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

    以下代码将:

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

    代码:

    // 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 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2021-07-02
      • 2015-10-08
      • 2015-04-20
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 2017-08-21
      • 2018-08-07
      相关资源
      最近更新 更多