纯代码实现 WordPress 显示文章最后更新时间的方法

本文教您如何使用代码实现 WordPress 显示文章最后更新时间的方法。

本文中的方法摘自博友奶爸de笔记《WordPress显示文章最后更新时间的方法》有改动。

相信很多朋友都有过去百度或者 Google 上搜索资料,尤其是偏技术性的资料。然后习惯性的会去阅读最新的教程文章。

而我们在发表文章后,即便对文章做了修改,也不会修改文章的发布时间,只会点击更新。所以就需要对访客有一个提醒,告诉他这篇文章最后是什么时间修改更新过的,避免访客一看发布日期是N年前,就直接关闭页面了,所以我们需要让 WordPress 显示文章最后更新时间,如下图所示。

纯代码实现 WordPress 显示文章最后更新时间的方法

第一步,把下面的代码添加到到主题的 functions.php 中。

//文章显示最后更新时间
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U'); 
$u_modified_time = get_the_modified_time('U'); 
$custom_content = ''; 
if ($u_modified_time >= $u_time + 86400) { 
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a'); 
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';  
} 
 
    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );

第二步,是设置最后更新时间的显示效果,把下面代码添加到你主题的 css 里面。

.last-updated {
    color: #db7c22;
background: #fff4b9;
border: 1px solid #eac946;
overflow: hidden;
margin: 10px 0;
padding: 15px 15px 15px 35px;
font-size: 14px;
}

要注意的是,只有文章修改时间超过24小时才会显示最后更新时间,如果你想修改间隔时间,修改打码里面的 86400即可。

按照以上代码显示的效果和我样图是有区别的,按照自己喜欢修改即可,懒得修改可以直接用下面的代码。

//文章显示最后更新时间
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U'); 
$u_modified_time = get_the_modified_time('U'); 
$custom_content = ''; 
if ($u_modified_time >= $u_time + 86400) { 
$updated_date = get_the_modified_time('Y-m-d');
$updated_time = get_the_modified_time('H:i'); 
$custom_content .= '<p class="last-updated">本文最后更新于 '. $updated_date . ',如您发现本文中的内容已失效请留言告知。</p>';  
} 
 
    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
点击查看更多「WordPress」专题文章
本站 [ 俍注 ] 内除注明转载文章,其他均为老俍独立创作,采用「CC BY-NC-ND 4.0」创作共享协议。
原创不易,希望保留原文链接转载,原文链接:https://oneinf.com/tech/yy/wp/4513.html
(1)
打赏 微信打赏 微信打赏 支付宝打赏 支付宝打赏
上一篇 2019-05-24
下一篇 2019-08-01

相关阅读

回复 慕仙

您的电子邮箱地址不会被公开。 必填项已用*标注

评论列表(11条)

  • 老杨
    老杨 2019-07-25

    我是把它显示在时间那里……有更新就把发布时间隐藏到 title……

  • 大致
    大致 2019-07-24

    如果是我写,我不会用the_content这个钩子。因为the_content是针对文章内容的。
    我会加在the_date或者get_the_date上。
    当然如果放在时间里文字内容放那么多就不好看了。
    如果非要在the_content上加这个钩子,那么优先度的那个参应该设大一点,不能用默认。因为针对the_content下手的函数太多了,现在的代码不能保证想加的东西加在最前面。

  • 执迷不悟
    执迷不悟 2019-07-24

    这个技巧比较实用,做个记号以备不时之需

  • 慕仙
    慕仙 2019-07-23

    这是个好东西啊。