WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

How to change the city field to a dropdown in WooCommerce

Today we will show you how to change the city field to a dropdown in WooCommerce. This works great for those of you who need to set up city-based shipping rates. As you may already know, it is possible to achieve this using my Advanced Shipping plugin. However, the downside of this is that your customers can enter their own values for the ‘Shipping Field’ which means that you’d have to enter any type of variation a customer can enter to ensure the correct shipping cost is calculated and shown at the totals.

The chances are that the customer makes a typo or enters a value that is not recognised by the values you set up for the shipping rates. A possible solution to this is to change the default text input field to a dropdown. This way you will have control over which options are available and the customer can enter, and ultimately, this can reduce the error rate at the checkout stage.

Changing the city field to a simple dropdown

The following code snippet will change the city field to a standard dropdown. You are able to set up both the display value to the customer and the so-called ‘index’ or ‘key’ which is what the ‘City’ condition will match against (when using the Advanced Shipping plugin).

The below code needs to go in your theme/child theme’s functions.php file:


<?php
/**
 * Change the checkout city field to a dropdown field.
 */
function city_dropdown_field( $fields ) {

	$city_args = wp_parse_args( array(
		'type' => 'select',
		'required' => true,
		'options' => array(
			'' => __( 'Select from list' ),
			'birmingham' => 'Birmingham',
			'cambridge' => 'Cambridge',
			'leicester'   => 'Leicester',
			'liverpool' => 'Liverpool',
			'london'    => 'London',
			'manchester'  => 'Manchester',			
		),
	), $fields['shipping']['shipping_city'] );

	$fields['shipping']['shipping_city'] = $city_args;
	$fields['billing']['billing_city'] = $city_args; // Also change for billing field

	return $fields;

}
add_filter( 'woocommerce_checkout_fields', 'city_dropdown_field' );

Let’s take this one step further and make the city select searchable…

Making a searchable city dropdown

If you have a large list of cities then it makes sense to add a searchable field, just like how the Country field works. Making it a searchable field can be done with a few additional lines of code.


<?php

// Copy from here

/**
 * Change the checkout city field to a dropdown field.
 */
function jeroen_sormani_change_city_to_dropdown( $fields ) {

	$city_args = wp_parse_args( array(
		'type' => 'select',
		'options' => array(
			'birmingham' => 'Birmingham',
			'cambridge' => 'Cambridge',
			'leicester'   => 'Leicester',
			'liverpool' => 'Liverpool',
			'london'    => 'London',
			'manchester'  => 'Manchester',
		),
		'input_class' => array(
			'wc-enhanced-select',
		)
	), $fields['shipping']['shipping_city'] );

	$fields['shipping']['shipping_city'] = $city_args;
	$fields['billing']['billing_city'] = $city_args; // Also change for billing field

	wc_enqueue_js( "
	jQuery( ':input.wc-enhanced-select' ).filter( ':not(.enhanced)' ).each( function() {
		var select2_args = { minimumResultsForSearch: 5 };
		jQuery( this ).select2( select2_args ).addClass( 'enhanced' );
	});" );

	return $fields;

}
add_filter( 'woocommerce_checkout_fields', 'jeroen_sormani_change_city_to_dropdown' );

This is how it looks with the searchable field:

Setting up shipping rates based on city

With this example, you can more easily set up rates based on the city field. Now you only have one variation the customer can enter instead of many different variations and prevent possibly typo’s. To setup city-based shipping using the ‘City’ condition, you can now enter the ‘key/index’ values set in the above code to match in the condition against what the user selects.

If you need any help setting this up, we’d love to help. Thanks for reading!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

27 thoughts on “How to change the city field to a dropdown in WooCommerce

  1. I did the same thing but for the address_2

    /**
    * Change the checkout address2 field to a dropdown field.
    */
    function address2_dropdown_field( $fields ) {

    $address2_args = wp_parse_args( array(
    ‘type’ => ‘select’,
    ‘options’ => array(
    ‘villa’ => ‘Villa’,
    ‘apartment’ => ‘Apartment’,
    ‘other’ => ‘Other’,
    ),
    ), $fields[‘shipping’][‘shipping_address_2’] );

    $fields[‘shipping’][‘shipping_address_2’] = $address2_args;

    return $fields;

    }
    add_filter( ‘woocommerce_checkout_fields’, ‘address2_dropdown_field’ );

  2. Hi Nathan!

    How can I do that with the state field? Im changing the name of the fields as so, it works for a millisecond when I refresh the checkout page (I can see the dropdown appears) but it reverts back to an input field.

    $fields[‘shipping’][‘shipping_state’] );

    $fields[‘shipping’][‘shipping_state’] = $city_args;
    $fields[‘billing’][‘billing_state’] = $city_args; // Also change for billing field

      1. How to add shipping rates based on city.
        could you please explain more detail custom code for this feature to be added for shipping only and shipping methods should be working on selective cities, also shipping cost for the cities should be editable according to the requirement?

  3. How to push data from exernal API to the options values? Once the state change, all the cities values change too. I was thingking to use jquery but where can I apply it?
    thanks

  4. I think I will implement this for Company Name as it seems every employee of a firm has a different way of typing it in so that makes it difficult to filter by company. However, I’m not going to think of every possible option. How would you go about adding an “Other” option and then a new box in which the user could type? Or is it possible to modify the code such that they could pick from the list or type a new one?

  5. Hi Nathan,
    Your plugin is great, I use it for Delivery to distritos in Lima.
    But I have the exact same question as Hassan asked here:
    “Hi,
    How do I add this to the woocommerce shopping cart – change address area”

    I cant figure out how to add a dropdown of Cities (distritos) in the shipping calculator that is on the shopping cart. Any help would be greatly appreciated.
    Thanks v much,
    Art

  6. Hi,

    Was wondering if it’s possible to have the dropdown not select an option by default and instead something like “Select from list”, therefore customers who are trying to submit the order fast, will not miss the field, as it’s already got an option selected.

    1. Hi, you can add an empty field at the start of the options, this will make this field required and set the default value to ‘Select from list’:

      
      $city_args = wp_parse_args( array(
      	'type' => 'select',
      	'required' => true,
      	'options' => array(
      		'' => __( 'Select from list' ),
      		'birmingham' => 'Birmingham',
      		'cambridge' => 'Cambridge',
      		'leicester'   => 'Leicester',
      		'liverpool' => 'Liverpool',
      		'london'    => 'London',
      		'manchester'  => 'Manchester',			
      	),
      ), $fields['shipping']['shipping_city'] );
      
  7. Yeah that would be great,

    Suppose when the Customer selects one of these cities, the shipping rate to that city will be added to the cart total. How that option can be added?

    Thanks,

    1. Agreed, but if you want to reduce the amount of bloat, sometimes less code is best. But it’s each to their own, thank you for your comment.

  8. Thank you for this snippet, how can I make the city select box content be only for a state, I mean, when a particular state A is selected, let it show the drop down list of cities, once another state is selected, let it hide the drop down and show the normal text box for user to type in the city manually.

  9. hi, I am using Shipping Rates by City for WooCommerce plugin, but the problem is when I add cities (I have so many cities or towns) i want the search box also in the drop down list for set the shipping rate based on Cities.
    what can I do?

Join the discussion