在 Woocommerce 中添加带有成人控件的结帐出生日期必填字段

Mau*_*tti 2 php wordpress checkout woocommerce

我需要在 Woocommerce 的帐单明细中添加出生日期的必填字段,并检查他们是否年满 18 岁。

我怎么办?

任何帮助表示赞赏。

Loi*_*tec 9

以下代码添加了账单出生日期字段,如果客户未满 18 岁,则将检查客户年龄以避免结账:

// Adding a custom checkout date field
add_filter( 'woocommerce_billing_fields', 'add_birth_date_billing_field', 20, 1 );
function add_birth_date_billing_field($billing_fields) {

    $billing_fields['billing_birth_date'] = array(
        'type'        => 'date',
        'label'       => __('Birth date'),
        'class'       => array('form-row-wide'),
        'priority'    => 25,
        'required'    => true,
        'clear'       => true,
    );
    return $billing_fields;
}


// Check customer age
add_action('woocommerce_checkout_process', 'check_birth_date');
function check_birth_date() {
    // Check billing city 2 field
    if( isset($_POST['billing_birth_date']) && ! empty($_POST['billing_birth_date']) ){
        // Get customer age from birthdate
        $age = date_diff(date_create($_POST['billing_birth_date']), date_create('now'))->y;

        // Checking age and display an error notice avoiding checkout (and emptying cart)
        if( $age < 18 ){
            wc_add_notice( __( "You need at least to be 18 years old, to be able to checkout." ), "error" );

            WC()->cart->empty_cart(); // <== Empty cart (optional)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 functiond.php 文件中。测试和工作。

在此处输入图片说明

  • @LoicTheAztec 此代码是否还会在管理区域的用户配置文件中显示该字段以及常规计费字段?该字段是否经过验证? (2认同)