wp_timezone_string()
云策文档标注
概述
wp_timezone_string() 函数用于获取站点的时区字符串,优先返回 timezone_string 选项值,否则回退到基于 gmt_offset 的 UTC 偏移量。
关键要点
- 函数返回 PHP 时区名称(如 'Europe/Rome')或 ±HH:MM 格式的偏移量(如 '+08:45')。
- 内部实现:先检查 timezone_string 选项,若未设置则根据 gmt_offset 计算偏移字符串。
- 相关函数:wp_timezone() 返回 DateTimeZone 对象,get_option() 用于获取选项值。
- 引入版本:WordPress 5.3.0。
代码示例
function wpdocs_custom_timezone_string() {
$timezone_string = get_option( 'timezone_string' );
$offset = (float) get_option( 'gmt_offset' );
$hours = (int) $offset;
$minutes = ( $offset - $hours );
$sign = ( $offset
原文内容
Retrieves the timezone of the site as a string.
Description
Uses the timezone_string option to get a proper timezone name if available, otherwise falls back to a manual UTC ± offset.
Example return values:
- ‘Europe/Rome’
- ‘America/North_Dakota/New_Salem’
- ‘UTC’
- ‘-06:30’
- ‘+00:00’
- ‘+08:45’
Source
function wp_timezone_string() {
$timezone_string = get_option( 'timezone_string' );
if ( $timezone_string ) {
return $timezone_string;
}
$offset = (float) get_option( 'gmt_offset' );
$hours = (int) $offset;
$minutes = ( $offset - $hours );
$sign = ( $offset < 0 ) ? '-' : '+';
$abs_hour = abs( $hours );
$abs_mins = abs( $minutes * 60 );
$tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );
return $tz_offset;
}
Changelog
| Version | Description |
|---|---|
| 5.3.0 | Introduced. |
Skip to note 2 content
Fida Al Hasan
/** * If you want to show both timezone_string & gmt_offset * Preview: Asia/Dhaka [+06:00] or +06:00 */ // function goes to theme's functions.php file or plugin's file function wpdocs_custom_timezone_string() { $timezone_string = get_option( 'timezone_string' ); $offset = (float) get_option( 'gmt_offset' ); $hours = (int) $offset; $minutes = ( $offset - $hours ); $sign = ( $offset < 0 ) ? '-' : '+'; $abs_hour = abs( $hours ); $abs_mins = abs( $minutes * 60 ); $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins ); $timezone = $timezone_string ? $timezone_string . ' [' . $tz_offset . ']' : $tz_offset; return $timezone; } // Usage echo esc_html( wpdocs_custom_timezone_string() );