为什么WooCommerce计费字段的有条件删除不起作用



我在functions.php文件中有以下代码,用于检查购物车中是否有某些产品,如果有,则在结账时从字段的账单集中删除一个字段。然而,它并没有删除字段,或者我尝试的任何其他字段。我想知道为什么会这样。我正在学习的其他教程都与这段代码一致,并说它应该有效,但对我来说不是。我做错了什么?

/**
* Check if a specific product ID is in the cart
*/
function dz_product_is_in_the_cart() {
// Add your special product IDs here
$ids = array( '10771', '10773', '10774', '10943', '10944', '10945', '10946', '10947', '10948', '10949', '10950', '10951', '10952', '10953', '10943', '10943', '10943', '10943');;
// 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;
}
}
/**
* Conditionally remove a checkout field based on products in the cart
*/
function dz_remove_checkout_field( $fields ) {
if ( dz_product_is_in_the_cart() ) {
unset( $fields['billing']['billing_first_name'] );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'dz_remove_checkout_field' );

billing_first_name字段是必填字段。那么,在尝试unset之前,我需要做些什么来取消对它的需求吗?

问题是插入此字段的插件覆盖了我试图取消请求并删除它的代码。我选择禁用该插件,并使用此处的代码添加并有条件地控制我自己的字段:https://woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-7

最新更新