In WooCommerce, you can use the woocommerce_checkout_fields filter to modify the checkout fields based on the selected payment method.

Here is an example of how you can use the woocommerce_checkout_fields filter to hide a custom field (e.g., “custom_field”) based on the selected payment method (e.g., “cod”):

Copy codeadd_filter( 'woocommerce_checkout_fields' , 'hide_custom_field_on_cod' );
function hide_custom_field_on_cod( $fields ) {
    $chosen_methods = WC()->session->get( 'chosen_payment_method' );
    $chosen_payment_method = $chosen_methods[0];
    if( $chosen_payment_method == 'cod' ){
        unset($fields['billing']['custom_field']);
    }
    return $fields;
}

This code uses the woocommerce_checkout_fields filter to modify the checkout fields, it gets the chosen payment method from the session and check the payment method is ‘cod’ or not, if yes, it will remove the “custom_field” from the billing section of the checkout fields.

You can also use the WC()->session->get( 'chosen_payment_method' ) to check the chosen payment method on the checkout page.

It’s important to note that you should use this code snippet on the checkout page and after the woocommerce_init action is fired, so that the WC() object is available.

Also, make sure that the custom field exists before trying to remove it,

(Visited 10 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window