We get loads of requests for customizations to different eCommerce platforms on WordPress. One that we receive on a super regular basis is for the ability to auto-populate the city, state and country just by entering the ZIP Code. This is a very US-centric feature, though it could be ported to any country. The concept really favors those businesses that sell primarily within their own country. That said, this segment comprises a very large portion of the eCommerce space.
So that said – how would you do this? It’s actually pretty easy. From a UX standpoint, you want to be sure that you’re showing the ZIP Code before you show the other fields – otherwise, it sort of defeats the purpose. WP eCommerce makes this super easy, but every platform is different.
Next, you’ll want to connect with a ZIP Code API of your choice. There are myriad different APIs to choose from, pick your favorite or whatever fits best for your purposes. For today, I’m going to use Zippopotamus. What I like about that service is that it actually works in over 60 different countries, not just the US, even though that’s our focus for today.
A user experience that I’ve come to really enjoy is the ability to fill in a ZIP Code, and then have it auto-fill and auto-show the city, state and country. The constant refrain against trying to be smart about ZIP Codes is “What if you get it wrong? What about ZIP Codes that cover multiple cities? What if the API fails?”
A simple UX is the key to all of these edge cases. Regardless of success or failure, simply show the extra fields once a response is received – or if none can be received at all. If it happens to return nothing, or the wrong thing, the user can simply fill in the right thing. But it’s a great improvement for the vast majority of visitors to your site. Now, for some code.
The code above is pretty well self-contained and self-explanatory. It’s not the prettiest thing ever, or the most complete, but it gets the job done. In essence, we’re simply adding three functions. One to show the city/state/country, one to hide it, and one to ping the API. We’re not doing any clever error handling. We’re simply pinging the API, and showing all the fields, no matter what. If we get a successful response, we’re filling in the fields with that information.
You’ll notice, if you’re familiar with WP eCommerce, that we’re not targeting any fields that exist in the stable version that exists in the wild today. We have a phenomenal new release coming out, version 4.0. It includes what I believe is the most usable checkout experience in any eCommerce platform for WordPress. We’re targeting elements within that new theme engine. Be sure to check that out.
With those ~35 lines of code, we have the experience you witness below. A totally usable