0
votes

I have conditionally unset the billing address fields on the woocommerce checkout page, but when submitting place order, woocommerce displays error:

Please enter an address to continue.

I then tried adding a filter on woocommerce_default_address_fields to make the fields optional - which only seems to work if the fields aren't unset.

    // make address fields optional - this works fine without the next filter
    add_filter( 'woocommerce_default_address_fields' , 'filter_default_address_fields', 20, 1 );
    function filter_default_address_fields( $address_fields ) {
       // Only on checkout page
       if( ! is_checkout() ) return $address_fields;

       // All field keys in this array
       $fields = array('country','company','address_1','address_2','city','state','postcode');

       // Loop through each address fields (billing and shipping)
       foreach( $fields as $key_field )
           $address_fields[$key_field]['required'] = false;

       return $address_fields;
    }

    //conditionally unset fields
    add_filter( 'woocommerce_checkout_fields' , 'simplify_checkout' );

    function simplify_checkout( $fields ) {

       $customField = false;
       foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
           // Check if cart item has attribute
           if (  ! empty ($cart_item['custom_attribute']) ) $registry = true;
       }
       if( $customField ) {
           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']);
       }
       return $fields;
    }

I'm hoping to still be able to conditionally hide / unset the fields along with a successful checkout submission.

1

1 Answers

1
votes

I had this problem with the validation message two days ago. I only sell to one country, so I created following workaround. Maybe if you have fewer countries to sell this could work for you too:

  1. Uncomment/Remove
    unset($fields['billing']['billing_country']);
  2. Go to WooCommerce -> Settings -> Sell to specific countries and enter your countries.
  3. Now the validation message is inactive, as the Country field is mandatory. You can remove it now with CSS.

    #billing_country_field { display: none; }