简介
最近一直在折腾这个玩意,折腾了两天终于折腾出了比较好看的一个更新时间提醒,借此机会记录下并分享给各位博主。先上图看效果:

图片来自我的一个测试站,专门用于测试新代码。
优点
可以让某些时效性很强的文章及时得到读者反馈,方便读者判断文中内容是否仍有效 (比如某些羊毛啊,线路啊等等)
实现代码
function wp_last_update ($content) {
$updated_date = get_the_modified_time('Y年n月j日');
$updated_time = get_the_modified_time('H:i');
$custom_content .= '
本文最后更新于 '
. $updated_date .' ' . $updated_time .'';
$custom_content .= $content;
return $custom_content;
}
add_filter('the_content','wp_last_update');
简单介绍下代码:
- $updated_date:文章最后更新日期,使用get_the_modified_time()函数获取,该函数将最后更新日期以指定格式输出,格式使用PHP时间戳格式,以上面的代码为例给出一个输出例子:2018年7月9日
- $updated_time:文章最后更新时间,使用get_the_modified_time()函数获取,该函数将最后更新时间以指定格式输出,格式使用PHP时间戳格式,以上面的代码为例给出一个输出例子:21:09
- $custom_content:提示的文本,可以自定义内容,需要使用HTML语句,最后与$content连接组成新的文章内容并返回
- $content:文章原本的内容
其实最上面那俩可以合并,但是我就是不合并(・・;)
常见bug:首页/目录也会显示最后更新时间
如逗比的站:

解决方案:返回内容时判断输出的地方是否是文章页,使用is_single()函数
将 return $custom_content;
改为 return is_single()?$custom_content:$content;
使用三元判断符来判断应该返回原本的内容还是增加最后修改时间的内容,效果如下图:

最终代码
function wp_last_update ($content) {
$updated_date = get_the_modified_time('Y年n月j日');
$updated_time = get_the_modified_time('H:i');
$custom_content .= '
本文最后更新于 '
. $updated_date .' ' . $updated_time .'';
$custom_content .= $content;
return is_single()?$custom_content:$content;
}
add_filter('the_content','wp_last_update');
美化小技巧
可以使用
来进行简单的美化,高大上的美化是采用CSS搭配
,比如效果图中我采用了Bootstrap4提供的"alert alert-secordary"加上少许文字颜色的变化修改而来的。