显示或隐藏基于WooCommerce中特定产品的结帐邮政编码字段



在WooCommerce中,每当选择特定产品时,我试图隐藏结帐时的邮政编码字段。我尝试了很多不同的方法。这是我最后一次尝试:

/**
* Conditionally remove a checkout field based on products in the cart
*/
function wc_ninja_product_is_in_the_cart() {
// Add your special product IDs here
$ids = array( '9531', '9072', '9035' );;
// 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_postcode'] );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' );
<!-- end snippet -->

/*Hide postal code field on checkout when specific product is selected.*/
function hide_postal_code_field_based_on_product( $fields ) {
$target_product_id = 385; // Your product ID
$product_found = false;
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $target_product_id ) {
$product_found = true;
break;
}
}
if ( $product_found ) {
$fields['billing']['billing_postcode']['class'][] = 'hide-postal-code';
}

return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'hide_postal_code_field_based_on_product' );
function hide_postal_code_field_css() {
?>
<style>
.hide-postal-code {
display: none !important;
}
</style>
<?php
}
add_action( 'woocommerce_checkout_after_customer_details', 'hide_postal_code_field_css' );

相关内容

最新更新