Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bookchiq/4cb5b11efd3d1dce1edb0825c60fc41c to your computer and use it in GitHub Desktop.
Save bookchiq/4cb5b11efd3d1dce1edb0825c60fc41c to your computer and use it in GitHub Desktop.
Add US Territories to the list of US States in Gravity Forms
<?php
/**
* Add US Territories to the list of US States in Gravity Forms.
*
* @param array $states The default list of states.
* @return array
*/
function filter_us_states( $states ) {
// Add American Samoa.
$previous_key = array_search( 'Alaska', $states, true );
$states = array_insert_after( $states, $previous_key, array( 'American Samoa' ) );
// Add Guam.
$previous_key = array_search( 'Georgia', $states, true );
$states = array_insert_after( $states, $previous_key, array( 'Guam' ) );
// Add Northern Mariana Islands.
$previous_key = array_search( 'North Dakota', $states, true );
$states = array_insert_after( $states, $previous_key, array( 'Northern Mariana Islands' ) );
// Add Puerto Rico.
$previous_key = array_search( 'Pennsylvania', $states, true );
$states = array_insert_after( $states, $previous_key, array( 'Puerto Rico' ) );
// Add U.S. Virgin Islands.
$previous_key = array_search( 'Texas', $states, true );
$states = array_insert_after( $states, $previous_key, array( 'U.S. Virgin Islands' ) );
return $states;
}
add_filter( 'gform_us_states', 'filter_us_states' );
/**
* Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended
* to the end of the array.
*
* @see https://gist.github.com/wpscholar/0deadce1bbfa4adb4e4c
*
* @param array $array
* @param string $key
* @param array $new
*
* @return array
*/
function array_insert_after( array $array, $key, array $new ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys );
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment