Skip to content

Look Up US State by Zip (Code Snippet)

Posted in Plugin Development, and WP Plugins

Hello! Just a quick code snippet today. Have you ever wanted to be able to input a US zipcode, and match it to a state? Or even match it to a county? A town? If so, then today’s snippet might be right up your ally. This snippet uses PHP to take an input as a zip code (does not have to be a valid zip code, or even numeric), and outputs the two letter state code if it is a valid US zipcode, or outputs null if it is not.

//function using regex to determine if format is the same as US zips
function pc_validate_zipcode($zipcode) {
	return preg_match('/^[0-9]{5}([- ]?[0-9]{4})?$/', $zipcode);

$initial_zip = 'yourziphere'; //enter or send your zip here
$valid_zip = pc_validate_zipcode($initial_zip); //returns true if the format is correct for US zip
$stateshort = ''; //this is what we'll be using at the end	
if ($valid_zip) {

	$us_lookup = new WP_Http(); //WP_Http function to connect

	//Google Geocode API address call
	$get_url = "$initial_zip";
	$us_response = $us_lookup -> get( $get_url);

	//Gets the body response from the API call and converts to an array
	$json_body = json_decode($us_response['body'],true);

	//gets the address components
	$address_components = $json_body['results']['0']['address_components'];

	$num_components = count($address_components);

	//Loops through address components, looking for the country code, and possibly the state
	for ($i=0;$i<$num_components;$i++) {

		if ($address_components[$i]['types']['0'] == 'country') {

			$country = $address_components[$i]['short_name'];
		} elseif ($address_components[$i]['types']['0'] == 'administrative_area_level_1') {

			$possible_state = $address_components[$i]['short_name'];


	//if the country code from the loop was US, then assign state 
	if ($country == 'US') {
		$stateshort = $possible_state;

echo "The state code is: $stateshort";

That's it! The code comments lay out each of the major steps within this snippet. If you want to pull other information such as the county, the town etc, just select the appropriate types from $address_components.