网站的页脚通常需要添加诸如“建站程序”,“主题作者”,“建站时间”,“版权声明”等相关版权信息。有的网站页脚显示的是建站时间,而有的则是网站运营时间如“2011-2012”这样的形式,即从建站开始到当前时间的一个动态版权时间。我们就通过代码可以给wordpress实现这个功能。
原始实现代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //原始代码有缺陷,不推荐 function comicpress_copyright() { global $wpdb; $copyright_dates = $wpdb->get_results(" SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb->posts WHERE post_status = 'publish' "); $output = ''; if($copyright_dates) { $copyright = "© " . $copyright_dates[0]->firstdate; if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) { $copyright .= '-' . $copyright_dates[0]->lastdate; } $output = $copyright; } return $output; } |
在需要显示版权的地方添加
1 | <?php echo comicpress_copyright(); ?> |
这段代码是网上流传的形式,其实现原理 :通过获取第一篇文章和最新发布文章的发布时间来确定年份,那么通过原理可知,代码缺点非常明显——依赖于发布体(如文章等post), 夸张一下,你一年两年甚至三年都没有发布新文章,版权时间将会出现错误,因为代码的功能是根据你的文章来确定年份。
那么如何取消这种依赖性,让运营版权时间更准确呢?往下看
优化版代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //显示网站运营版权时间 function auto_copyright() { global $wpdb; $first = $wpdb->get_results(" SELECT user_registered FROM $wpdb->users ORDER BY ID ASC LIMIT 0,1 "); $output = ''; $current = date(Y) ; if($first) { $first=date(Y,strtotime($first[0]->user_registered)); $copyright = "© " . $first; if($first != $current) { $copyright .= '-' .$current; } $output = $copyright; } echo $output; } |
原理:按照id升序排序,获取第一位用户的注册时间提取年份(网站第一位用户肯定是网站所有者自己了),获取当前时间提取年份。
注意,这里我们不用ID=1进行匹配查询,因为个别站长的做法是:后期添加自己然后删除原有管理员admin,其ID不是1.
代码使用说明
1.将Timle提供的实现代码添加到主题的function.php文件中,方法大家已经熟悉了,“?>”之前。
2.编辑footer.php文件,在你需要显示的地方添加上调用代码
1 | <?php auto_copyright(); ?> |
2017年7月24日 下午5:42 沙发
好吧好吧,你是来干啥来了
2017年7月24日 下午5:58 板凳
好