get_post_timestamp()
云策文档标注
概述
get_post_timestamp() 函数用于获取文章发布或修改时间的 Unix 时间戳,返回纯 Unix 时间戳,不包含时区偏移。
关键要点
- 函数返回 Unix 时间戳,成功时返回 int,失败时返回 false
- 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post 对象
- 参数 $field 可选,指定使用数据库中的发布时间('date')或修改时间('modified'),默认为 'date'
- 内部调用 get_post_datetime() 获取 DateTimeImmutable 对象,再转换为时间戳
- 自 WordPress 5.3.0 版本引入,用于替代旧函数中带时区偏移的时间戳
代码示例
// 获取文章发布时间戳
$published_timestamp = get_post_timestamp( $post_id, 'date' );
// 获取文章修改时间戳
$modified_timestamp = get_post_timestamp( $post_id, 'modified' );
// 将时间戳转换为可读格式
$published_date = date_i18n( get_option( 'date_format' ), $published_timestamp );
$modified_date = date_i18n( get_option( 'date_format' ), $modified_timestamp );注意事项
- 返回的是纯 Unix 时间戳,不同于旧版 WordPress 函数中可能包含时区偏移的时间戳
- 确保传入有效的 $post 参数,否则可能返回 false
- 结合 date_i18n() 函数可将时间戳格式化为本地化日期字符串
原文内容
Retrieves post published or modified time as a Unix timestamp.
Description
Note that this function returns a true Unix timestamp, not summed with timezone offset like older WP functions.
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'.
Source
function get_post_timestamp( $post = null, $field = 'date' ) {
$datetime = get_post_datetime( $post, $field );
if ( false === $datetime ) {
return false;
}
return $datetime->getTimestamp();
}
Changelog
| Version | Description |
|---|---|
| 5.3.0 | Introduced. |
Skip to note 2 content
Sam Kent
How to get the published and modified date with
get_post_timestamp()and then convert it into a readable format.