2024 年 4 月 28 日 我的频道
WP 显示编辑的日期时间
  • 2022
  • Sunny

做网站的朋友都有那么的经历,就是文章发布后,会有重新修改编辑的可能性。为了吸引读者能够清晰的知道该文章的修改更新,最好的方法就是展现文章的修改日期,可以让读者一眼看见更新时间,尤其是对代码或者是资源的更新,这个功能是必不可少的。

我的站点上在文章列表循环以及在文章内部,都清晰的标注了文章的更新时间,如果文章没有编辑过,那么只显示发布的时间;如果文章发布过后又重新编辑过,那么就显示编辑更新的时间,颜色和图标也不相同,这样更能吸引大家的眼球。先来一段代码,实现了文章更新后的时间显示,这里的代码与官方所说的一样,不同的是我把中文显示的方式弄成英文缩写的方式:

<?php
 if ( get_the_modified_time( 'U' ) >= get_the_time( 'U' ) + 86400 ) {
            echo '<div class="updated">';
            echo date( 'M', get_the_modified_time( 'U' ) ) . ' ' . get_the_modified_time( 'd, Y' );
            echo '</div>';
          } else {
            echo '<div class="dates">';
            echo date( 'M', get_the_time( 'U' ) ) . ' ' . get_the_time( 'd, Y' );
            echo '</div>';
          }
?>

以上的代码很明确,判断文章发布的时间和编辑的时间,如果编辑的时间大于发布的时间,则显示编辑的时间。

再来一段在独立文章显示的更新文章时间提示,把代码放到 Functions.php 里面去:

// 文章最后更新时间
    function wpb_last_updated_date() {
    
    $u_time = get_the_time('U'); 
    $u_modified_time = get_the_modified_time('U'); 
    if ($u_modified_time >= $u_time + 86400) { 
    $updated_date = date ('M',get_the_modified_time('U')).' '.get_the_modified_time('d, Y');
    $updated_time = get_the_modified_time('h:i A'); 
    echo '
<div class="post-last-update">Last UpDated On <u>'. $updated_date . ' At '. $updated_time .'</u></div>
';  
    } 
    } 

一个让人痛恨的是,Wordpress 的中文版本显示的时间是:上午,下午,不能显示英文的 AM,PM。翻遍了 Google,找不到有一个可以解决的方案,于是灵机一动,调取了字符替换的功能来让心里平衡一下,功能是用最简单的方式实现,但是希望用程序来实现起来,暂时先应付着吧,上代码:

function replace_text_wps( $text ) {
  $replace = array(
    // '关键词' => '替换的关键词'  
    '上午' => 'AM',
    '下午' => 'PM',

  );
  $text = str_replace( array_keys( $replace ), $replace, $text );
  return $text;
}

add_filter( 'get_the_modified_time', 'replace_text_wps' );

更新于 2023-9-4,添加一个 24 小时制的代码:

// 文章最后更新时间改为 24 小时制
function wpb_last_updated_date() {
	$u_time = get_the_time('U');
	$u_modified_time = get_the_modified_time('U');
	if ($u_modified_time >= $u_time + 86400) {
		$updated_date = date('M d, Y', get_the_modified_time('U'));
		$updated_time = date('H:i:s', get_the_modified_time('U')); // 修改时间格式为 24 小时制
		echo '
<div class="post-last-update">Last Updated On '. $updated_date . ' At '. $updated_time .'</div>
';
	}
}

至此,显示文章判断编辑修改的功能就此结束!

STUDY
964
0

Author Box

名字:Sunny
注册:Jan 30, 2021
简介:技术菜鸟,拷贝、黏贴代码中 ……

Comment Box

0 0 投票数
Article Rating
订阅评论
提醒
guest

0 评论
内联反馈
查看所有评论