skip to Main Content

How do you make both City and Suburb fields required in WooCommerce Shipping Calculator

enter image description here

3

Answers


  1. Chosen as BEST ANSWER

    I can copy the shipping-calculator.php template to my child theme and then add the 'required' attribute to both the postcode and city input fields which prevents the field from being empty, that works fine.

        <p class="form-row form-row-wide" id="calc_shipping_city_field">
            <input type="text" required class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_city() ); ?>" placeholder="<?php esc_attr_e( 'City', 'woocommerce' ); ?>" name="calc_shipping_city" id="calc_shipping_city" />
        </p>
    <?php endif; ?>
    
    <?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_postcode', true ) ) : ?>
        <p class="form-row form-row-wide" id="calc_shipping_postcode_field">
            <input type="text" required class="input-text" value="<?php echo esc_attr( WC()->customer->get_shipping_postcode() ); ?>" placeholder="<?php esc_attr_e( 'Postcode / ZIP', 'woocommerce' ); ?>" name="calc_shipping_postcode" id="calc_shipping_postcode" />
        </p>
    <?php endif; ?>
    

    If it's possible to do via a WooCommerce php snippet I'd like to know, rather that than the template way.


  2. Or, validate data via the filter.

    add_filter( 'woocommerce_cart_calculate_shipping_address', function( $address ){ 
        if ( empty( $address['postcode'] ) && empty( $address['city'] ) ) {
            throw new Exception( __( 'Please enter a postcode and a city name' ) );
        } elseif ( empty( $address['postcode'] ) ) {
            throw new Exception( __( 'Please enter a postcode' ) );
        } elseif ( empty( $address['city'] ) ) {
            throw new Exception( __( 'Please enter a city name' ) );
        }
        return $address;
    });
    
    Login or Signup to reply.
  3. Also possible by jQuery in a document ready function…

    $('#calc_shipping_city, #calc_shipping_postcode').prop('required', true);
    

    This would avoid using a woocommerce template.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search