Search States by Abbreviation – WooCommerce

Have you noticed that by default the WooCommerce billing state dropdown only searches by the state’s full name and not by the abbreviation? Recently one of our clients came to us with a request to make their ecommerce website’s billing state dropdown searchable by both the state name and state abbreviation. And it turns out that it is fairly simple to search states by abbreviation. The end result turned out so nicely that we wanted to share our solution with you!

WooCommerce State Dropdown
Example of trying to find a state in the dropdown.

Why is this Important?

First, let’s go over why it is important to search states by full name and the abbreviation. A customer attempted to enter their state’s abbreviation into the state dropdown and was confused when the dropdown would only filter by the state’s full name and not by its abbreviation. As an example, if they were trying to find Missouri but had tried using the state abbreviation of “MO” then the dropdown would have returned “Montana” and “Vermont”, but not Missouri.

Attempting to search a state dropdown by state abbreviations.
Searching for the state of Missouri by its abbreviation. With the default settings it doesn’t work.

Technically you don’t need to search by abbreviation for your customers to make a purchase. (In fact, this website ran for years before this issue was brought to our attention.) So why did we feel it was important to search the dropdown by both the state name and state abbreviation? Primarily because for some customers it disrupted their train of thought and intent to make a purchase to the extent that they almost didn’t finish their purchase. It only takes a few moments to add our custom code to your website and if it speeds along just a few purchases it will have been worth the time it took to install it. And secondly, it adds a nice, polished feel to the checkout process.

The Custom Code for Searching by Abbreviation

Simply add the following code to your theme’s functions.php file. Usually this file is located in /wp-content/themes/YOUR_THEME/functions.php.

// Update the State dropdown in "Billing Details" so that the user can type and search by both state name and abbreviation
add_action('woocommerce_before_cart', 'BillingStateSelectizeUpdateOptions');
add_action('woocommerce_before_checkout_form', 'BillingStateSelectizeUpdateOptions');
function BillingStateSelectizeUpdateOptions() {
    $js_script = "
        jQuery(document).ready(function() {
            var state_search_params = {
                matcher: function(params, data) {
                
                    var term = params.term || '';
                    var text = data.text || '';
                    var id = data.id || '';
                
                    // If there are no search terms, return all of the data
                    if (term.trim() === '') {
                        return data;
                    }
                    // Do not display the item if there is no 'text' property
                    if (typeof data.text === 'undefined') {
                        return null;
                    }
                
                    if (text.toLowerCase().indexOf(term.toLowerCase()) > -1) {
                        return (data);
                    }
                    else if (id.toLowerCase().indexOf(term.toLowerCase()) > -1) {
                        return (data);
                    }
                    
                    return null;
                }
            };
            
            jQuery('#billing_state, #shipping_state, #calc_shipping_state').selectWoo(state_search_params);
        });
    ";
    
    wp_register_script('search-billing-state-dropdown', '', array(), '', true);
    wp_enqueue_script('search-billing-state-dropdown');
    wp_add_inline_script('search-billing-state-dropdown', $js_script);
}

Understanding the Code

Let’s break down why this code works. And to do that we have to understand how the state selection box normally works. WooCommerce uses the selectWoo library fork of the Select2 jQuery replacement for select boxes. This allows us to replace our basic dropdowns with a much more dynamic searchable dropdown. However, by default the WooCommerce state select dropdown only searches by the visible text of each option which is the state’s full name. The option values contain the state abbreviations. Our code works by updating the selectWoo options with our new and improved search code.

In order to update the selectWoo options we use WooCommerce action hooks to call a function that will output our custom JavaScript on the cart and checkout pages. We wrap our JavaScript itself in a jQuery(document).ready(); function. This ensures that our code will only run AFTER the necessary JS libraries have been loaded. In particular, this code must run AFTER WooCommerce sets its default settings.

Our JavaScript code is extremely simple. It contains an object with “matcher” function that will override WooCommerce’s text matching function. The function simply checks the search term against both the select option text and values (also known as the option ID). This allows us to search the states by full name (option text) or by abbreviation (optional value). Finally, we apply our new and improved search parameter to all elements matching known WooCommerce state dropdown IDs. That would be the Billing State and Shipping State fields.

To output our JS code to the page we register the script, enqueue the script, and set the script to our defined JS script variable. Please note that when calling the wp_register_script() function we set the $in_footer parameter to TRUE so that our script loads at the bottom of the page and not at the top. This parameter will ensure that the required JS libraries are included before our custom code is run.

Testing the Search Results

If everything goes well then you should now be able to search your states by both the full state names or abbreviations. Allowing your users to search by state abbreviation will make a smooth addition to your website and quite possibly make the buying experience more enjoyable for your customers.

Successful search of state by abbreviation!
Successfully searching for the state of Missouri by its abbreviation! After applying our custom code snippet.

Troubleshooting Searching States by Abbreviation

Every website is different and unique. And because of that this code may need slightly adaptation to work on your website. Here are some possible solutions to try if the code snippet does not allow .

  • Check the IDs of the select dropdown elements. We designed this code snippet to work with the state dropdowns that have an ID of “billing_state“, “shipping_state“, or “calc_shipping_state“. If your state dropdown does not have one of these IDs then add it to the jQuery selector.
  • Change the add_action() priority to queue the script to load further down the page. The JavaScript might be loading too soon in the page and being overridden by the default WooCommerce settings. Move the snippet down the page so that it will run when it is supposed to.
  • Contact us for help. You might be facing an issue we didn’t account for. Send us a message and we will update our code.

Need more help? Check out our knowledge base for more help articles or contact us for help with your website.

Sign up to get our latest articles

Don’t worry. We won’t sell your email. We are also really busy managing our clients, so we won’t be filling your inbox with articles every day. We only write them when we have a compelling reason to do so, and some spare time too!

preloader