How to make both City and Postcode fields required in WooCommerce Shipping Calculator

Both the City and Postcode/ZIP fields in the WooCommerce Shipping Calculator are not compulsory for the user to fill in, you may need them mandatory for a better user experience to calculate certain shipping conditions.

Woocommerce City Postcode Fields

Both the Suburb and Postcode fields are input fields inside a form which allows us to use the required attribute, this will force the user to fill out the field before the form is submitted with a small tool tip will display telling the user the field is required.

Adding the required field using a WooCommerce template

You can add the required fields by copying the shipping-calculator.php template from:

/woocommerce/templates/cart/shipping-calculator.php

to…

/yourtheme/woocommerce/cart/shipping-calculator.php

Then in your version add in the required fields:im

		<?php if ( apply_filters( 'woocommerce_shipping_calculator_enable_city', true ) ) : ?>
			<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; ?>

Now if not filled in, the user will see:

Woocommerce Compulsory Shipping Fields

Adding the required field using jQuery

You can also add the required attribute in with jQuery, in a document ready function use:

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

This may be better to use if you don’t want to manage WooCommerce child templates.

2 Comments

  1. Lindsey John on May 17, 2023 at 6:00 am

    Great tutorial! Your solution to making both the city and postcode fields required in the WooCommerce shipping calculator is fantastic. The step-by-step instructions and code snippets made it easy to implement. Thank you for sharing your expertise!

  2. Zahid on March 16, 2023 at 10:46 pm

    Thanks for the solution

Leave all Comment