Wordpress - How to get WordPress Time Zone setting?
if you need the gmt_offset then
<?php echo get_option('gmt_offset'); ?>
this will give you an integer like 2 or -2.
and if you need the timezone string use
<?php echo get_option('timezone_string'); ?>
this will give you a string like America/Indianapolis
The unfortunate situation is that there are indeed two different options:
- Newer
timezone_string
, which saves PHP–style time zone. - Older
gmt_offset
, which saves numeric float offset in hours.
But in newer environments timezone_string
actually overrides gmt_offset
, the value returned by the latter will be based on the former. However the opposite isn't true — gmt_offset
might be valid, while timezone_string
is empty.
WordPress 5.3 had shipped wp_timezone()
function, that abstracts this and returns a valid DateTimeZone
object, regardless of underlying WP settings.
Before that I had a take on it implemented in my WpDateTime
library (for trivia that was used as a basis for core implementation):
class WpDateTimeZone extends \DateTimeZone {
/**
* Determine time zone from WordPress options and return as object.
*
* @return static
*/
public static function getWpTimezone() {
$timezone_string = get_option( 'timezone_string' );
if ( ! empty( $timezone_string ) ) {
return new static( $timezone_string );
}
$offset = get_option( 'gmt_offset' );
$hours = (int) $offset;
$minutes = abs( ( $offset - (int) $offset ) * 60 );
$offset = sprintf( '%+03d:%02d', $hours, $minutes );
return new static( $offset );
}
}
Check the Option Reference page. The option gmt_offset
returns an integer. For example, if the timezone is set to Eastern time (e.g. America/New_York), gmt_offset
should be -5.