我們在很多網站都會看到此文章幾天前發布或幾分鐘前發布,如果要wordpress實現這功能,我們只要在functions文件中加一個php處理代碼即可,首先在主題的 functions.php 文件中加入以下代碼:
- function timeago( $ptime ) {
- $ptime = strtotime($ptime);
- $etime = time() - $ptime;
- if ($etime < 1) return '剛剛';
- $interval = array (
- 12 * 30 * 24 * 60 * 60 => '年前 ('.date('Y-m-d', $ptime).')',
- 30 * 24 * 60 * 60 => '個月前 ('.date('m-d', $ptime).')',
- 7 * 24 * 60 * 60 => '周前 ('.date('m-d', $ptime).')',
- 24 * 60 * 60 => '天前',
- 60 * 60 => '小時前',
- 60 => '分鐘前',
- 1 => '秒前'
- );
- foreach ($interval as $secs => $str) {
- $d = $etime / $secs;
- if ($d >= 1) {
- $r = round($d);
- return $r . $str;
- }
- };
- }
列表頁和文章頁面使用方法,適用于如下文件:
- index.php
- search.php
- tag.php
- single.php
- page.php
- author.php
- category.php
在需要顯示時間的地方替換成以下,注意需要放在?php代碼塊中,代碼如下:
echo '發表于 '.timeago( get_gmt_from_date(get_the_time('Y-m-d G:i:s')) );
評論區域使用方法:在需要顯示時間的地方替換成以下,注意需要放在評論循環內:
echo '發表于 '.timeago( $comment->comment_date_gmt );
其他:當然,你還可以更改函數中的文字以達到你自己的需求,此函數傳值格式為“2013-11-11 11:11:11”,只要格式符合就行,但是wp有gmt時間制,所以才有了以上使用方式,后現再網上找了一個同樣是加在functions.php文件中,顯示新增文章的時間格式為“幾分鐘”前,代碼如下:
- function timeago() {
- global $post;
- $date = $post->post_date;
- $time = get_post_time('G', true, $post);
- $time_diff = time() - $time;
- if ( $time_diff > 0 && $time_diff < 24*60*60 )
- $display = sprintf( __('%s ago'), human_time_diff( $time ) );
- else
- $display = date(get_option('date_format'), strtotime($date) );
- return $display;
- }
- add_filter('the_time', 'timeago');//這個就是調用方法了
新聞熱點
疑難解答
圖片精選