墨轩
[资讯杂谈]为WordPress网站添加文章过时失效提示
实现原理
输出WordPress数据库中存储的文章最后更新时间字段,并与访问者访问时间对比,如果访问时间大于最后更新时间+一天,则输出文章失效提示,反之则不输出。这里的1天可以自行定义。为了方便大家使用,我这里提供了两种方式,自行选择。
钩子函数挂载
利用WordPress提供的the_content()钩子挂载。当然,这样会导致所有页面中及摘要中都会出现提示。不建议使用此方法
使用方法:
在functions.php
文件中加入如下代码
//文章过期提示
function article_time_update($content) {
date_default_timezone_set('PRC');
$newdate=time();
$updated_date = get_the_modified_time('Y-m-d H:i:s');
$updatetime=strtotime($updated_date);
$custom_content = '';
if ( $newdate > $updatetime+86400) {
$custom_content= '<div class="article-timeout"><strong>重要:</strong>本文最后更新于<code>'. $updated_date . '</code>,某些文章具有时效性,若有错误或已失效,请在下方<a href="#comment">留言</a>或联系<a target="_blank" title="代码狗博客" href="https://www.daimadog.com/about"><b>代码狗</b></a>。</div >';
}
echo $custom_content.$content;
}
add_action('the_content','article_time_update');
[scode type="yellow"]不建议使用此方法,因为部分主题可能会在摘要部分显示提示信息![/scode]
直接调用函数
如果你只需要文章提示,那么可以直接修改下你的文章模板single.php
,在the_content()
函数之前调用下如下函数。
先将下面的函数代码加入到你的functions.php
文件中。
//文章过期提示
function article_time_update() {
date_default_timezone_set('PRC');
$newdate=time();
$updated_date = get_the_modified_time('Y-m-d H:i:s');
$updatetime=strtotime($updated_date);
$custom_content = '';
if ( $newdate > $updatetime+86400) {
$custom_content= '<div class="article-timeout"><strong>重要:</strong>本文最后更新于<code>'. $updated_date . '</code>,某些文章具有时效性,若有错误或已失效,请在下方<a href="#comment">留言</a>或联系<a target="_blank" title="代码狗博客" href="https://www.daimadog.com/about"><b>代码狗</b></a>。</div >';
}
echo $custom_content;
}
在single.php
文件中找到the_content()
函数,并在其之前加上article_time_update()
即可。
具体效果如本站文章页面,下面是我的css
.article-timeout {
position: relative;
color: #999;
margin-bottom: 25px;
padding: 15px;
background-color: #fbfbfb;
border-top: 1px solid #f0f0f0;
border-bottom: 1px solid #f0f0f0;
}
版权属于:赵墨轩部落格
本文链接:https://www.zmxcn.cn/1105.html
本文章采用「知识共享署名-相同方式共享 4.0 国际许可协议」进行许可。转载时须注明出处及本声明