我正在寻找一种方法,我可以添加一些代码到我的wordpress模板中,以相对术语显示帖子的时间。例如,如果我在5分钟前发布了一些内容,那么它会说一些与6分钟前、2天前或1周前发布的内容大致相同的内容。你明白了。有谁能给我一些指导,告诉我怎么做?
Relative Time On Posts
2 个回复
最合适的回答,由SO网友:John P Bloch 整理而成
WordPress实际上有一个鲜为人知的函数,名为human_time_diff()
就是这样。它有两个论点;第一个是较早的时间戳,第二个是较晚的时间戳。两者都应该是Unix时间戳。第一个参数是必需的,但第二个是可选的,将使用time()
如果留空。例如,在循环中,可以执行以下操作:
<p>Posted <?php echo human_time_diff( get_the_time( \'U\' ) ); ?> ago.</p>
不过,该函数只能执行分钟、小时和天。例如,如果你需要休息几周,你可以这样做:$diff = explode( \' \', human_time_diff( get_the_time( \'U\' ) ) );
if( $diff[1] == \'days\' && 7 <= $diff[0] ){
$diff[1] = \'week\';
$diff[0] = round( (int)$diff[0] / 7 );
if( $diff[0] > 1 )
$diff[1] .= \'s\';
$diff = implode( \' \', $diff );
}
那会让你N week(s)
作为字符串。SO网友:onetrickpony
您也可以尝试time_since()
功能:
function time_since($older_date, $newer_date = false){
$chunks = array(
\'year\' => 60 * 60 * 24 * 365,
\'month\' => 60 * 60 * 24 * 30,
\'week\' => 60 * 60 * 24 * 7,
\'day\' => 60 * 60 * 24,
\'hour\' => 60 * 60,
\'minute\' => 60,
\'second\' => 1
);
$newer_date = ($newer_date == false) ? (time()+(60*60*get_option("gmt_offset"))) : $newer_date;
$since = $newer_date - $older_date;
foreach ($chunks as $key => $seconds)
if (($count = floor($since / $seconds)) != 0) break;
$messages = array(
\'year\' => _n(\'%s year ago\', \'%s years ago\', $count),
\'month\' => _n(\'%s month ago\', \'%s months ago\', $count),
\'week\' => _n(\'%s week ago\', \'%s weeks ago\', $count),
\'day\' => _n(\'%s day ago\', \'%s days ago\', $count),
\'hour\' => _n(\'%s hour ago\', \'%s hours ago\', $count),
\'minute\' => _n(\'%s minute ago\', \'%s minutes ago\', $count),
\'second\' => _n(\'%s second ago\', \'%s seconds ago\', $count),
);
return sprintf($messages[$key],$count);
}
可以这样称呼它:echo time_since(abs(strtotime($post->post_date." GMT"));
我想this 是代码的原始源代码结束