Mau*_*tti 2 php wordpress checkout woocommerce
我需要在 Woocommerce 的帐单明细中添加出生日期的必填字段,并检查他们是否年满 18 岁。
我怎么办?
任何帮助表示赞赏。
以下代码添加了账单出生日期字段,如果客户未满 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 文件中。测试和工作。
| 归档时间: |
|
| 查看次数: |
5267 次 |
| 最近记录: |