1,351   WordPress

 

320press模板显示文章发布时间使用the_time($string) 函数,它会根据参数$string 来显示对应的时间格式,比如’Y-m-d G:i:s’ 之类的。

$string为空时,只显示对应格式’G:i’的时间,觉得好奇怪,于是搜索了一下the_time()函数,发现在根目录下的wp-includes文件夹下的general-temptlate.php 文件

function the_time( $d = ” ) {

echo apply_filters(‘the_time’, get_the_time( $d ), $d);

}

继续查看get_the_time()函数,就在下面

function get_the_time( $d = ”, $post = null ) {

$post = get_post($post);

 

if ( ” == $d )

$the_time = get_post_time(get_option(‘time_format’), false, $post, true);

else

$the_time = get_post_time($d, false, $post, true);

return apply_filters(‘get_the_time’, $the_time, $d, $post);

}

来到这里就明白了,当the_time($string)函数为空时,即get_the_time($d)中的$d为空时,就只取get_option(‘time_format’)格式的时间,’time_format’对应的是一天时间即24小时的时间格式,另外还有’date_format’,对应是年月日的时间格式,这个在后台设置里都可以看到。

 

如果想在the_time($string)参数为空时显示更详细的时间,那么只需修改get_the_time($d)函数中下面这行

$the_time = get_post_time(get_option(‘time_format’), false, $post, true);

修改为

$the_time = get_post_time(get_option(‘date_format’).’,’.get_option(‘time_format’), false, $post, true);

我修改显示年月日以及24小时时间即’Y-d-m G:i’,这个可以根据自己需要修改。

另外,我们也可以自己定制自己的the_time($sting),想微博那样显示对应的时间,参考以下链接内容

http://85ryan.com/wordpress/weibo-time-format.html

参考新浪微博的时间显示方式,将wordpress文章的发布时间显示如下格式:

  • 文章发布时间在1分钟之内,显示“刚刚”;
  • 文章发布时间大于1分钟小时1小时,则显示“xx分钟前”;
  • 文章发布时间大于1小时但在当天之内,则显示“今天 xx:xx”;
  • 文章发布时间在今天之前,但在今年之内,则显示“xxxx日 xx:xx;
  • 文章发布时间在今年之前的,则显示“xxxxxxxx日”;

实现方式为:在functions.php中加入以下代码:

[php]/** 微博时间格式化显示 **/
function time_since() {
global $post;
$date = $post->post_date;
$time = get_post_time(G, true, $post);
$since = abs(time()-$time);
if(floor($since/3600)){
if(date(Y-m-d,$time) == date(Y-m-d,time())){
$output = ‘今天 ‘;
$output.= date(H:i,strtotime($date));
}else{
if(date(Y,$time) == date(Y,time())){
$output = date(md日 H:i,strtotime($date));
}else{
$output = date(get_option(date_format), strtotime($date) );
}
}
}else{
if(($output=floor($since/60))){
$output = $output.’分钟前’;
}else $output = ‘刚刚’;
}
return $output;
}
add_filter(the_timetime_since);[/php]

然后在文章中要显示文章发布时间的地方使用函数

[php]<?php the_time(); ?>[/php]

调用时间就可以了!

 

但要注意某些模板中有使用the_time()函数,所以在自己定制时做好兼容性修改,不要覆盖了原来函数的功能。

 

 

更多资料

http://hi.baidu.com/webzl/item/0657983295ad85d51a969640




Leave a Reply

Your email address will not be published. Required fields are marked *