Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Change Postcode Shipping Field to a Dropdown in WooCommerce?

Are you shipping products to limited postcodes and want to show only those as a drop-down on the WooCommerce PIN Code field? The code given below will help you to achieve this customization on both shipping and billing fields.

add_filter( 'woocommerce_default_address_fields' , 'ts_customize_postcode_fields' );

function ts_customize_postcode_fields( $address_fields ) {
    $address_fields['postcode']['type'] = 'select';
    $address_fields['postcode']['options'] = array(
        ''         => __('Select your postcode', 'woocommerce'),
        '560043'   => '560043',
        '560038'   => '560038',
        '560025'   => '560025'
    );

    // Add custom validation callback
    $address_fields['postcode']['validate'] = array('ts_validate_postcode');

    return $address_fields;
}

// Custom validation callback
function ts_validate_postcode( $postcode, $field ) {
    // Check if the selected option is not empty and is a valid postcode
    if ( ! empty( $postcode ) && ! in_array( $postcode, array('560043', '560038', '560025') ) ) {
        // Display an error if the postcode is not valid
        throw new Exception( __( 'Please select a valid postcode.', 'woocommerce' ) );
    }

    return $postcode;
}

Output

The below output shows a PinCode field with a dropdown of postcodes listed in the code.

How to Change Postcode Shipping Field to a Dropdown in WooCommerce?

Similar to the above customization, you can also change the city field to a drop down in the WooCommerce shipping calculator by replacing the default text field.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
3 Comments
Newest
Oldest
Inline Feedbacks
View all comments
ritesh
8 days ago

not working

RITESH
6 days ago
Reply to  Saranya

THANKS, ITS WORKING NOW.

3
0
Would love your thoughts, please comment.x
()
x