get_post_datetime()
云策文档标注
概述
get_post_datetime() 函数用于获取文章的发布时间或修改时间,返回一个 DateTimeImmutable 对象实例。该对象会根据 WordPress 设置中的时区进行配置,并支持从数据库中的本地时间或 UTC 时间实例化,以确保向后兼容性。
关键要点
- 函数返回 DateTimeImmutable 对象,失败时返回 false
- 参数 $post 可选,默认为全局 $post 对象,可接受文章 ID 或 WP_Post 对象
- 参数 $field 可选,指定使用发布时间('date')或修改时间('modified'),默认为 'date'
- 参数 $source 可选,指定从数据库中使用本地时间('local')或 UTC 时间('gmt'),默认为 'local'
- 函数内部处理时区转换,最终返回的对象时区与 WordPress 站点时区一致
代码示例
function get_post_datetime( $post = null, $field = 'date', $source = 'local' ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$wp_timezone = wp_timezone();
if ( 'gmt' === $source ) {
$time = ( 'modified' === $field ) ? $post->post_modified_gmt : $post->post_date_gmt;
$timezone = new DateTimeZone( 'UTC' );
} else {
$time = ( 'modified' === $field ) ? $post->post_modified : $post->post_date;
$timezone = $wp_timezone;
}
if ( empty( $time ) || '0000-00-00 00:00:00' === $time ) {
return false;
}
$datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', $time, $timezone );
if ( false === $datetime ) {
return false;
}
return $datetime->setTimezone( $wp_timezone );
}注意事项
- 由于历史原因,$source 参数允许选择从本地或 UTC 时间实例化,通常结果无差异,但在时区设置变更导致数据库值不同步时,可用于确保向后兼容行为
- 如果时间值为空或 '0000-00-00 00:00:00',函数将返回 false
- 相关函数包括 wp_timezone()、get_post()、get_post_timestamp()、get_post_time() 和 get_post_modified_time()
- 该函数自 WordPress 5.3.0 版本引入
原文内容
Retrieves post published or modified time as a DateTimeImmutable object instance.
Description
The object will be set to the timezone from WordPress settings.
For legacy reasons, this function allows to choose to instantiate from local or UTC time in database.
Normally this should make no difference to the result. However, the values might get out of sync in database, typically because of timezone setting changes. The parameter ensures the ability to reproduce backwards compatible behaviors in such cases.
Parameters
$postint|WP_Postoptional-
Post ID or post object. Default is global
$postobject.Default:
null $fieldstringoptional-
Published or modified time to use from database. Accepts
'date'or'modified'.
Default'date'. $sourcestringoptional-
Local or UTC time to use from database. Accepts
'local'or'gmt'.
Default'local'.
Source
function get_post_datetime( $post = null, $field = 'date', $source = 'local' ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$wp_timezone = wp_timezone();
if ( 'gmt' === $source ) {
$time = ( 'modified' === $field ) ? $post->post_modified_gmt : $post->post_date_gmt;
$timezone = new DateTimeZone( 'UTC' );
} else {
$time = ( 'modified' === $field ) ? $post->post_modified : $post->post_date;
$timezone = $wp_timezone;
}
if ( empty( $time ) || '0000-00-00 00:00:00' === $time ) {
return false;
}
$datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', $time, $timezone );
if ( false === $datetime ) {
return false;
}
return $datetime->setTimezone( $wp_timezone );
}
Changelog
| Version | Description |
|---|---|
| 5.3.0 | Introduced. |