在WordPress外掛庫查找外掛時,偶爾會看到提示說外掛已經超過 2 年沒有更新……如果我們想在WordPress老文章頂部顯示類似的提示信息,比如超過 1 年沒有更新的文章,就提示某些信息,如下圖所示:
實現的方法很簡單,將下面的代碼添加到當前主題的 functions.php 文件即可:
1 2 3 4 5 6 7 8 9 10 11 |
//添加老文章提示信息 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 > 365 ){ $content = '<div class="old-message">本文最後更新於'.get_the_modified_time('Y年n月j日').',已超過 1 年沒有更新,如果文章內容失效,請反饋給我們,謝謝!</div>'.$content; } return $content; } add_filter( 'the_content', 'wpdaxue_old_content_message' ); |
//添加老文章提示信息 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 > 365 ){
$content = ‘<div class="old-message">本文最後更新於’.get_the_modified_time(‘Y年n月j日’).’,已超過 1 年沒有更新,如果文章內容失效,請反饋給我們,謝謝!</div>’.$content;
}
return $content;
}
add_filter( ‘the_content’, ‘wpdaxue_old_content_message’ );
以上代碼的第 3 行使用瞭 get_the_modified_time() 函數來獲取文章的最後修訂時間,如果你的文章在發佈後進行過修改,比如修改標簽、內容等都會更新時間。第 6 行的 365 是天數,第 7 行 是自定義信息,請根據自己的需要修改。
如果隻想在特定的分類顯示提示,比如隻在 ID 為 4 的分類的文章顯示提示信息,可以將第 6 行代碼修改為:
1 |
if($diffTime > 365 && in_category(4) ){ |
if($diffTime > 365 && in_category(4) ){
如果是多個分類,比如在 ID 為 4、7、9的分類文章顯示提示信息,可以使用數組形式:
1 |
if($diffTime > 365 && in_category(array(4,7,9)) ){ |
if($diffTime > 365 && in_category(array(4,7,9)) ){
如果要排除某些分類,比如在 ID 為 4、7、9 以外的分類文章顯示提示信息,可在 in_category 前添加“!”:
1 |
if($diffTime > 365 && !in_category(array(4,7,9)) ){ |
if($diffTime > 365 && !in_category(array(4,7,9)) ){
順便可以在css文件添加下樣式,可以達到配圖效果:
1 |
.old-message{padding:10px;color: #DB7C22;font-size: 14px;background: #FFFCEF;border: solid 1px #FFBB76;border-radius: 2px;box-shadow: 0 0 3px #ddd;} |
.old-message{padding:10px;color: #DB7C22;font-size: 14px;background: #FFFCEF;border: solid 1px #FFBB76;border-radius: 2px;box-shadow: 0 0 3px #ddd;}