![](/img/trans.png)
[英]Conditionally hide a Checkout field in WooCommerce based on chosen shipping
[英]Add conditionally a custom checkout field to shipping section in WooCommerce
我有某些 Woocommerce 產品需要客戶(或產品接收者)提供出生日期。 客戶在創建帳戶以結帳時需要提供出生日期,所以我都設置在那里,但是如果選中“運送到不同的地址”並且如果有任何項目,我需要在運送部分添加一個必填的 DOB 字段購物車中有一個需要出生日期的地方。
這是我嘗試過的:
add_filter( 'woocommerce_checkout_fields' , 'real_dob' );
function real_dob( $fields ) {
$fields['shipping']['real_dob'] = array(
'type' => 'text',
'class'=> array( 'form_right_half', 'req'),
'label' => __('Birthdate'),
'required' => true,
);
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$dob_check = get_post_meta( $cart_item['product_id'], 'require-dob', true );
if ( $dob_check == 1 ) {
$dob = true;
break;
}}
if ($dob)
return $fields;
}
這適用於購物車中的產品需要出生日期 - 添加了自定義字段。 但是,如果購物車中沒有任何產品需要 DOB,那么結帳字段中的任何一個都不會加載,無論是計費還是運輸。 我錯過了什么?
由於當購物車不包含 DOB 產品時過濾器不會返回任何內容,因此它在結帳中既不顯示帳單也不顯示運輸字段。
您可以像這樣修改代碼:
add_filter( 'woocommerce_checkout_fields' , 'real_dob' );
function real_dob( $fields ) {
//if(cart DOES NOT contain any DOB products)
if(true)
{
return $fields;
}
//if(cart contains DOB products)
else
{
$fields['shipping']['real_dob'] = array(
'type' => 'text',
'class'=> array( 'form_right_half', 'req'),
'label' => __('Birthdate'),
'required' => true,
);
return $fields;
}
}
剛剛測試並且工作正常。 祝你有美好的一天。
在過濾器鈎子中,您需要始終在最后返回第一個函數參數,即$fields
。 嘗試以下功能更簡單的方法:
add_filter( 'woocommerce_checkout_fields' , 'add_real_dob_checkout_field' );
function add_real_dob_checkout_field( $fields ) {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for 'require-dob' custom field
if( get_post_meta( $cart_item['product_id'], 'require-dob', true ) == 1 ) {
$fields['shipping']['real_dob'] = array(
'type' => 'text',
'class'=> array( 'form_right_half', 'req'),
'label' => __('Birthdate'),
'required' => true,
);
break; // Stop the loop
}
}
return fields; // Always return the main function argument at the end for a filter hook
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.