我们使用 WordPress 编辑文章的时候都会有一个发布时间,正常情况下都会在文章页或列表页中显示文章对应的发布时间,有时候还需要将发布时间与修改时间作对比然后判断是展示发布时间还是修改时间或其他,这个时候就需要用到 get_the_time()函数了,这个函数就是今天的重点内容。
get_the_time()函数介绍
检索(获取)当前文章的发布时间。
get_the_time( string $format = '', int|WP_Post $post = null )
参数:
$format(string):(可选)用于检索撰写文章时间的格式。“G”,“U”或 PHP 日期格式默认为 time_format 选项中指定的值。默认值:''
$post(int|WP_Post):(可选)WP_Post 对象或 ID,默认为全局$post 对象。默认值:null
返回:
(string|int|false) 格式化的日期字符串或 Unix 时间戳,如果$format 是'U'或'G'。错误的失败。
函数所在文件:wp-includes/general-template.php
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 );
return apply_filters( 'get_the_time', $the_time, $format, $post );
}
get_the_time()函数使用示例
示例:使用 WordPress 默认格式返回当前帖子的时间,并使用 PHP echo 命令显示它。
示例:以 WordPress 默认格式返回 ID 为$ post-> ID 的帖子的时间。
<?php echo get_the_time( '', $post->ID ); ?>
示例:将以秒为单位的当前帖子的本地时间(自 1970 年 1 月 1 日以来,被称为 Unix Epoch)分配给变量$ u_time。
示例:如通过判断文章发布时间和最后修改时间来添加一些提示,如『WordPress 如何实现多久时间后在文章最后添加更新时间?』。
以上内容整理自@WordPress - get_the_time()