WordPress超过一定时间的老文章顶部显示自定义信息

在WordPress插件库查找插件时,偶尔会看到提示说插件已经超过 2 年没有更新……如果我们想在WordPress老文章顶部显示类似的提示信息,比如超过 1 年没有更新的文章,就提示某些信息,如下图所示:

custom-message-on-old-posts-wpdaxue_com

实现的方法很简单,将下面的代码添加到当前主题的 functions.php 文件即可:

//添加<a href="https://www.wpdaxue.com/tag/%e8%80%81%e6%96%87%e7%ab%a0" title="查看与【老文章】相关的文章" target="_blank" rel="noopener">老文章</a>提示信息 From wpdaxue.com
function wpdaxue_old_content_message($content) {
	$modified = get_the_modified_time('U'); 
	$current = current_time('timestamp');
	$diffTime = ($current - $modified) / (60*60*24); 
	if($diffTime &gt; 365 ){
		$content = '&lt;div class=&quot;old-message&quot;&gt;本文最后更新于'.get_the_modified_time('Y年n月j日').',已超过 1 年没有更新,如果文章内容失效,请反馈给我们,谢谢!&lt;/div&gt;'.$content;
	}
	return $content;
}
add_filter( 'the_content', 'wpdaxue_old_content_message' );

以上代码的第 3 行使用了 get_the_modified_time() 函数来获取文章的最后修订时间,如果你的文章在发布后进行过修改,比如修改标签、内容等都会更新时间。第 6 行的 365 是天数,第 7 行 是自定义信息,请根据自己的需要修改。

如果只想在特定的分类显示提示,比如只在 ID 为 4 的分类的文章显示提示信息,可以将第 6 行代码修改为:

	if($diffTime &gt; 365 &amp;&amp; in_category(4) ){

如果是多个分类,比如在 ID 为 4、7、9的分类文章显示提示信息,可以使用数组形式:

	if($diffTime &gt; 365 &amp;&amp; in_category(array(4,7,9)) ){

如果要排除某些分类,比如在 ID 为 4、7、9 以外的分类文章显示提示信息,可在 in_category 前添加“!”:

	if($diffTime &gt; 365 &amp;&amp; !in_category(array(4,7,9)) ){

顺便可以在css文件添加下样式,可以达到配图效果:

.old-message{padding:10px;color: #DB7C22;font-size: 14px;background: #FFFCEF;border: solid 1px #FFBB76;border-radius: 2px;box-shadow: 0 0 3px #ddd;}

来源:

https://www.wpdaxue.com/add-custom-message-on-old-posts.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32779.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?