Hide custom meta field based on cart weight

69 Views Asked by At

For a WooCommerce shop, based on a Shipping Zone I have three custom fieldgroups showing at checkout. I want to hide two of those fieldgroups depending on the total weight of the Cart.

By default the checkout shows all three fieldgroups because they are tied to the same shipping zone.

Three weight categories: upto 500kg (Should just show this fieldgroup meta name) _review_order_before_payment_blue_zone_500)

501-1000kg (Should just show this fieldgroup meta name) _review_order_before_payment_collection_blue_zone_500_1000

1001+kg (Should just show this fieldgroup meta name) _review_order_before_payment_collection_blue_zone_1001

This is the code I've cobbled together, but its not hiding the fieldgroup. Any ideas?

// Unset checkout field based on cart weight
add_filter('woocommerce_checkout_fields', 'remove_custom_checkout_field', 999 );
function remove_custom_checkout_field( $fields ) {
    if ( WC()->cart->get_cart_contents_weight() >= 500 ) {
        unset($fields['_review_order_before_payment_collection_blue_zone_500_1000']); // Unset field
    }
    if ( WC()->cart->get_cart_contents_weight() >= 1001 ) {
        unset($fields['_review_order_before_payment_collection_blue_zone_1001']); // Unset field
    }
    return $fields;
}

Expected fieldgroups to disappear when weight was calculated.

1

There are 1 best solutions below

0
On

This is how you should declare field based on if its billing, shipping, order etc. Read more about here - https://woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/

In my case my weight is set to kg and testing product is 0.5kg. You can add your condition in custom_woocommerce_billing_fields and skip remove_checkout_fields_by_weight function.

add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields($fields)
{
    $fields['billing_test'] = array(
        'label' => __('Test field', 'woocommerce'),
        'placeholder' => _x('', 'placeholder', 'woocommerce'), 
        'required' => false, 
        'clear' => false, 
        'type' => 'text',
        'class' => array('my-css')
    );
    return $fields;
}

function remove_checkout_fields_by_weight( $fields ) {
    if ( WC()->cart->get_cart_contents_weight() >= 0.5 ) {
        unset( $fields['billing']['billing_test'] );
    }
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'remove_checkout_fields_by_weight' );