今天小編給大家介紹一篇文章是關于WordPress修改時間的顯示格式為幾天前,WordPress 本身調用時間的函數 the_time() 只能直接調用時間,通過他的 filter,我們可以讓他顯示為比較科學的幾天前格式。
將下邊的代碼添加到 function.php 的最后一個 ?> 前即可。
/**
* WordPress 修改時間的顯示格式為幾天前
*/
function Bing_filter_time(){
global $post ;
$to = time();
$from = get_the_time('U') ;
$diff = (int) abs($to - $from);
if ($diff <= 3600) {
$mins = round($diff / 60);
if ($mins <= 1) {
$mins = 1;
}
$time = sprintf(_n('%s 分鐘', '%s 分鐘', $mins), $mins) . __( '前' , 'Bing' );
}
else if (($diff <= 86400) && ($diff > 3600)) {
$hours = round($diff / 3600);
if ($hours <= 1) {
$hours = 1;
}
$time = sprintf(_n('%s 小時', '%s 小時', $hours), $hours) . __( '前' , 'Bing' );
}
elseif ($diff >= 86400) {
$days = round($diff / 86400);
if ($days <= 1) {
$days = 1;
$time = sprintf(_n('%s 天', '%s 天', $days), $days) . __( '前' , 'Bing' );
}
elseif( $days > 29){
$time = get_the_time(get_option('date_format'));
}
else{
$time = sprintf(_n('%s 天', '%s 天', $days), $days) . __( '前' , 'Bing' );
}
}
return $time;
}
add_filter('the_time','Bing_filter_time');
上邊的代碼可以讓 30 天內發布的文章顯示為幾天前,而過了 30 天即顯示為正常的標準格式日期。
新聞熱點
疑難解答