John Davidson

php - Woocommerce condition to hide fields if cart = $0

0 comments
Message:


I'm trying to make sure that certain billing information fields are unset if the product is virtual and the cart amounts to $0. I'm having trouble with the second condition. I've tried using conditions from other posts on stackoverflow, but run into a weird issue where all fields are removed if the cart != 0


add_filter( 'woocommerce_checkout_fields' , 'bbloomer_simplify_checkout_virtual' );

function bbloomer_simplify_checkout_virtual( $fields ) {
$only_virtual = true;

global $woocommerce;
if ($woocommerce->cart->get_cart_total() != 0 ) {
return;
}

foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Check if there are non-virtual products
if ( ! $cart_item['data']->is_virtual() ) $only_virtual = false;
}

if( $only_virtual ) {
unset($fields['billing']['billing_company']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_address_2']);
unset($fields['billing']['billing_city']);
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_country']);
unset($fields['billing']['billing_state']);
unset($fields['billing']['billing_phone']);
add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );
}

return $fields;
}


My Answer:
>cart->total == 0) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['data']->is_virtual() ) {
$only_virtual = true;
} else {
$only_virtual = false;
break;
}
}
} else {
$only_virtual = false;
}

if ( $only_virtual ) {
unset( $fields['billing']['billing_first_name'] );
unset( $fields['billing']['billing_last_name'] );
unset( $fields['billing']['billing_company'] );
unset( $fields['billing']['billing_address_1'] );
unset( $fields['billing']['billing_address_2'] );
unset( $fields['billing']['billing_city'] );
unset( $fields['billing']['billing_postcode'] );
unset( $fields['billing']['billing_country'] );
unset( $fields['billing']['billing_state'] );
unset( $fields['billing']['billing_phone'] );
unset( $fields['order']['order_comments'] );
}

return $fields;
}

Rate this post

4 of 5 based on 2821 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us