Skip to content

Instantly share code, notes, and snippets.

@userabuser
Last active December 15, 2021 14:48
Show Gist options
  • Save userabuser/a8fedb9eedb24350b29f6c8302d1ebf0 to your computer and use it in GitHub Desktop.
Save userabuser/a8fedb9eedb24350b29f6c8302d1ebf0 to your computer and use it in GitHub Desktop.
Returns an associative array of timezone choices grouped by continent or context.
<?php
if ( ! function_exists( 'wp_util_get_timezone_choices' ) ) :
/**
* Returns an associative array of timezone choices grouped by continent or context.
*
* WordPress does not provide a static list of timezone choices or core function to return
* an array of timezone choices that have been optionally translated and free from their
* surrounding HTML markup as otherwise returned by WP core function wp_timezone_choice().
*
* @uses wp_timezone_choice()
*
* @param string $locale Optional. Locale to load the timezones in. Default current site locale.
* @return array|bool Array of timezone choices grouped by continent or context, false otherwise.
*/
function wp_util_get_timezone_choices( $locale = null ) {
$timezones_choices = wp_timezone_choice( null, $locale );
preg_match_all( '/(?:\<option value\=\")(.*)(?:\")/', $timezones_choices, $matches );
if ( ! isset( $matches[1] ) ) {
return false;
}
$timezones = array();
foreach ( $matches[1] as $zone ) {
$value = $label = $group = $zone;
$zone = explode( '/', $zone );
if ( count( $zone ) > 1 ) {
$group = array_shift( $zone );
$label = implode( ' - ', $zone );
} elseif ( strpos( $value, 'UTC' ) !== false ) {
$label = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $value );
$group = 'UTC';
}
$timezones[ $group ][] = array(
'value' => $value,
'label' => $label,
);
}
return $timezones;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment