預設的 WordPress 時間格式(如「2023年10月15日」)雖然準確,但缺乏即時感。將時間顯示為「3分鐘前」、「2小時前」、「1天前」等相對時間,能讓訪客直觀感知內容的新鮮度,增強互動體驗,尤其適合高頻更新的部落格或資訊站點。
human_time_diff()WordPress 內建 human_time_diff( $from, $to ) 函數可計算兩個時間戳差異,並以人類可讀格式返回(如「1小時」、「5分鐘」)。
<?php echo human_time_diff( get_comment_time('U'), current_time('timestamp') ); ?>
直接使用此函數會將所有時間轉為相對格式,但超過幾天的舊內容顯示「XX天前」不夠直觀,需進階判斷。
<?php
$diff = current_time('timestamp') - get_comment_time('U');
if ( $diff < 86400 ) { // 86400 秒 = 1 天
$cmt_time = human_time_diff( get_comment_time('U'), current_time('timestamp') ) . ' ago';
} else {
$cmt_time = get_comment_date('Y/n/j') . ' - ' . get_comment_time('', '', false);
}
echo $cmt_time;
?>
中文版 WordPress 會將 human_time_diff 結果強制漢化,可能破壞佈局。解決方案是自定義函數 xz_time_diff,將單位首字母大寫(Min/Hour/Day)避開翻譯機制。
<?php
// 加入 functions.php
if ( ! function_exists( 'xz_time_diff' ) ) :
function xz_time_diff( $from, $to = '' ) {
if ( empty($to) ) $to = time();
$diff = (int) abs($to - $from);
if ($diff <= 3600) {
$mins = round($diff / 60); if ($mins <= 1) $mins = 1;
$since = sprintf(_n('%s Min', '%s Mins', $mins), $mins);
} elseif ($diff <= 86400) {
$hours = round($diff / 3600); if ($hours <= 1) $hours = 1;
$since = sprintf(_n('%s Hour', '%s Hours', $hours), $hours);
} else {
$days = round($diff / 86400); if ($days <= 1) $days = 1;
$since = sprintf(_n('%s Day', '%s Days', $days), $days);
}
return $since;
}
endif;
?>
調用方式:
<?php
if ( current_time('timestamp') - get_comment_time('U') < 86400 ) {
$cmt_time = xz_time_diff( get_comment_time('U'), current_time('timestamp') ) . ' ago';
} else {
$cmt_time = get_comment_date('Y/n/j') . ' - ' . get_comment_time('', '', false);
}
echo $cmt_time;
?>
xz_time():統一處理文章與評論將以下代碼加入主題 functions.php,即可在模板中靈活調用。
<?php
if ( ! function_exists( 'xz_time' ) ) :
function xz_time( $type = 'art', $ago_time = 86400, $after = ' - ago', $late = '' ) {
if ( $type === 'cmt' ) {
$diff = (int) abs( get_comment_time('U') - current_time('timestamp') );
$late = $late ?: get_comment_time('Y/n/j - H:i');
} elseif ( $type === 'art' ) {
$diff = (int) abs( get_the_time('U') - current_time('timestamp') );
$late = $late ?: get_the_time('Y/n/j - H:i');
}
if ( $diff <= 3600 ) {
$mins = round($diff / 60); if ($mins <= 1) $mins = 1;
$since = sprintf(_n('%s Min', '%s Mins', $mins), $mins);
} elseif ($diff <= 86400) {
$hours = round($diff / 3600); if ($hours <= 1) $hours = 1;
$since = sprintf(_n('%s Hour', '%s Hours', $hours), $hours);
} else {
$days = round($diff / 86400); if ($days <= 1) $days = 1;
$since = sprintf(_n('%s Day', '%s Days', $days), $days);
}
$since .= $after;
return $diff < $ago_time ? $since : $late;
}
endif;
?>
// 評論時間:1天內顯示相對時間,超過顯示預設格式
echo xz_time('cmt');
// 輸出範例:3 Hours-ago / 2015/12/26 - 20:01
// 評論時間:2天內顯示相對時間,後綴「之前的評論」
echo xz_time('cmt', 172800, '之前的評論');
// 輸出範例:3 Hours 之前的評論 / 2015/12/26 - 20:01
// 文章時間:自定義超時後格式為 年-月-日
echo xz_time('art', 86400, ' ago', get_the_time('Y-n-j'));
通過層層遞進的優化,從簡單的 human_time_diff 到功能完善的 xz_time(),我們實現了:
將封裝函數加入 functions.php,即可在主題任意位置輕鬆調用,顯著提升用戶體驗。