在WooCommerce结帐表单中,我自定义了字段。但是,如果产品属于特定类别,我不希望显示这些字段。我有那部分工作。
接下来我想取消一些自定义结帐字段,但我无法弄清楚如何或现在。取消设置正常的结帐字段很简单,我使用例如以下代码:
unset( $fields['billing']['billing_company'] );
但是对于自定义结帐字段,它不起作用。以下是我设置此自定义字段的方法:
function company_details_section($checkout)
{
woocommerce_form_field('delegate_1_name', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide delegateExists'
) ,
'label' => __('Full name') ,
) , $checkout->get_value('delegate_1_name'));
}
由于这属于它自己的部分,而不是结算,发货或普通的WooCommerce附加字段,我找不到删除它的方法。
我尝试了以下内容:
unset( $fields['delegate_1_name'] );
unset( $fields['additional']['delegate_1_name'] );
unset( $fields['billing']['delegate_1_name'] );
unset( $fields['shipping']['delegate_1_name'] );
unset( $fields['company_details_section']['delegate_1_name'] );
这是我用来取消设置字段的条件函数:
function wc_ninja_product_is_in_the_cart() {
// Add your special product IDs here
$ids = array( '45', '70', '75' );;
// Products currently in the cart
$cart_ids = array();
// Find each product in the cart and add it to the $cart_ids array
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$cart_product = $values['data'];
$cart_ids[] = $cart_product->id;
}
// If one of the special products are in the cart, return true.
if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
return true;
} else {
return false;
}
}
这是取消设置正常结帐字段的功能代码:
function wc_ninja_remove_checkout_field( $fields ) {
if ( ! wc_ninja_product_is_in_the_cart() ) {
unset( $fields['billing']['billing_company'] );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' );
如何在WooCommerce(不是经典的)中取消设置自定义结帐字段?
答案 0 :(得分:1)
您无法取消设置自定义结帐字段,因为它未在数组中设置,例如默认的经典WooCommerce结帐字段。
因此,您应该直接在自定义字段创建代码中使用条件函数。我还重新审视了一下你现有的代码:
// Conditional function: If one of the special products is in cart return true, else false
function is_in_cart() {
// Add your special product IDs here
$ids = array( 45, 70, 75 );
foreach( WC()->cart->get_cart() as $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
if( in_array( $cart_item['data']->get_id(), $ids ) )
return true;
}
return false;
}
add_filter( 'woocommerce_checkout_fields' , 'remove_checkout_fields', 10, 1 );
function remove_checkout_fields( $fields ) {
if( ! is_in_cart() )
unset($fields['billing']['billing_company']);
return $fields;
}
add_action( 'woocommerce_after_order_notes', 'company_details_section', 10, 1 );
function company_details_section( $checkout ){
// Here your conditional function
if( is_in_cart() ){
echo '<div id="my_custom_checkout_field"><h3>' . __('Company Details') . '</h3>';
woocommerce_form_field( 'delegate_1_name', array(
'type' => 'text',
'class' => array( 'my-field-class form-row-wide delegateExists' ),
'label' => __('Full name') ,
) , $checkout->get_value( 'delegate_1_name' ) );
echo '</div>';
}
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
经过测试,适用于自2.5.x以来的所有WooCommerce版本