好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

wordpress实现文章和评论日期显示几分钟之前几小

wordpress实现文章和评论日期显示几分钟之前几小时之前

我们在很多网站都会看到此文章几天前发布或几分钟前发布,如果要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' ); //这个就是调用方法了  

查看更多关于wordpress实现文章和评论日期显示几分钟之前几小的详细内容...

  阅读:52次