Roman Selin
Roman Selin

Reputation: 119

Required Checkout Field Based on Shipping Method - Woocommerce

I'd like to make billing_last_name not required if local pickup is chosen.

Trying something like this:

function xa_remove_billing_checkout_fields($fields) {
    $shipping_method ='local_pickup'; // Set the desired shipping method to hide the checkout field(s).
    global $woocommerce;
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

    if ($chosen_shipping == $shipping_method) {
       $fields['billing']['billing_last_name'][ 'required' ] = false;
    }
    return $fields;
}

But it's not working.

Is there a proper solution?

Upvotes: 0

Views: 2121

Answers (1)

user4055330
user4055330

Reputation:

Here's your updated code with a hook:

add_filter('woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields');

function xa_remove_billing_checkout_fields($fields) {
    $shipping_method ='local_pickup'; // Set the desired shipping method to hide the checkout field(s).
    global $woocommerce;
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

    if ($chosen_shipping == $shipping_method) {
       $fields['billing']['billing_last_name'][ 'required' ] = false;
    }
    return $fields;
}

Upvotes: 4

Related Questions