[英]Show custom checkout fields if a specific product is in cart on Woocommerce
So I have some custom fields in my billing section on the checkout page, that I only want to display if a product with ID (603) is in the cart. 因此,我在结帐页面的“结算”部分中有一些自定义字段,如果购物车中有ID(603)的产品,我只想显示这些字段。
Currently, my code below works to hide the fields if there is a product in the cart that is not id 603, but one issue is when I have 603 and another product in the cart it unsets the fields, 当前,如果购物车中有一个不是id 603的产品,那么下面的代码可以隐藏字段,但是一个问题是,当我的购物车中有603和另一个产品时,它会取消设置字段,
what is the best way to either hide the fields if 603 is not in the cart or to just show them if it is? 隐藏603(如果不在购物车中)或仅显示(如果显示)这些字段的最佳方法是什么?
this is the current code I was using 这是我正在使用的当前代码
function conditional_checkout_fields_products( $fields ) {
$cart = WC()->cart->get_cart();
foreach ( $cart as $item_key => $values ) {
$product = $values['data'];
if ( $product->id != 603 ) {
unset( $fields['billing']['billing_prev_injuries'] );
unset( $fields['billing']['billing_dogs_events'] );
unset( $fields['billing']['billing_dogs_age'] );
unset( $fields['billing']['billing_dogs_breed'] );
unset( $fields['billing']['billing_dogs_name'] );
}
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );
The following will do the job: 以下将完成工作:
add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_products' );
function conditional_checkout_fields_products( $fields ) {
$is_in_cart = false;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == 603 ) {
$is_in_cart = true;
break;
}
}
if ( ! $is_in_cart ) {
unset( $fields['billing']['billing_prev_injuries'] );
unset( $fields['billing']['billing_dogs_events'] );
unset( $fields['billing']['billing_dogs_age'] );
unset( $fields['billing']['billing_dogs_breed'] );
unset( $fields['billing']['billing_dogs_name'] );
}
return $fields;
}
Code goes in function.php file of your active child theme (or active theme). 代码进入您的活动子主题(或活动主题)的function.php文件中。 Tested and works. 经过测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.