get_the_time()
云策文档标注
概述
get_the_time() 函数用于获取文章的发布时间,支持自定义格式和指定文章对象。它返回格式化后的时间字符串或 Unix 时间戳,失败时返回 false。
关键要点
- 参数 $format 可选,接受 'G'、'U' 或 PHP 日期格式,默认使用 'time_format' 选项
- 参数 $post 可选,接受文章 ID 或 WP_Post 对象,默认使用全局 $post 对象
- 返回值类型为 string|int|false,具体取决于 $format 参数
- 内部调用 get_post_time() 函数获取时间,并应用 'get_the_time' 过滤器
- 相关函数包括 get_post_time()、apply_filters()、get_option() 和 get_post()
代码示例
// 基本示例:获取并显示当前文章的默认格式时间
echo get_the_time();
// 获取指定文章 ID 的时间
$post_time = get_the_time( '', $post->ID );
// 获取 Unix 时间戳
$u_time = get_the_time( 'U' );注意事项
- 若需 GMT 时间戳,建议使用 get_post_time() 函数并设置 $gmt 参数为 true
- 函数自 WordPress 1.5.0 版本引入,兼容性良好
原文内容
Retrieves the time of the post.
Parameters
$formatstringoptional-
Format to use for retrieving the time the post was written. Accepts
'G','U', or PHP date format.
Defaults to the'time_format'option. $postint|WP_Postoptional-
Post ID or post object. Default is global
$postobject.Default:
null
Source
function get_the_time( $format = '', $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$_format = ! empty( $format ) ? $format : get_option( 'time_format' );
$the_time = get_post_time( $_format, false, $post, true );
/**
* Filters the time of the post.
*
* @since 1.5.0
*
* @param string|int $the_time Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
* @param string $format Format to use for retrieving the time the post
* was written. Accepts 'G', 'U', or PHP date format.
* @param WP_Post $post Post object.
*/
return apply_filters( 'get_the_time', $the_time, $format, $post );
}
Hooks
- apply_filters( ‘get_the_time’, string|int $the_time, string $format, WP_Post $post )
-
Filters the time of the post.
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 3 content
Codex
Basic Example
Returns the time of the current post using the WordPress default format, and displays it using the PHP echo command.
Returns the time of the post with ID $post->ID in the WordPress default format.
ID ); ?>Skip to note 4 content
Codex
Getting Unix Timestamp
Assigns the local time of the current post in seconds (since January 1 1970, known as the Unix Epoch) to the variable $u_time.
In most cases, you would probably want the epoch time for GMT (rather than for the local time zone), which you can get with the get_post_time() function, setting the $gmt option to true: