在我第一次进入 boke112 的时候,就被它首页的“每评论一次就会自动排在本栏目和对应博客导航分类页面第一位”深深吸引住了。然后我也想弄出这样一个功能,但是 boke112 分享的《WordPress 博客导航实现最新评论自动排第一功能》是 WordPress 教程,而我使用的是 Typecho,所以只能找人帮我写,但写出来的结果并不理想,有很多 bug。
第一次做这个功能是两个月前的事情,群里的一位小哥帮我写的,那时候的 bug 很多,经常出现网址错误、名字错误和空白等。现在周末闲着没事干,就把这个功能修复了一下,虽然这代码看起来就这么几十行,但我花了很多精力在上面,我没学过 PHP,所以每个函数都是查百度查了很久才查出来的。(被迫学习。)现在我又忘了这些函数是什么意思了,不管了,反正能用就行。
这是我在本博客里使用的效果:
我感觉这效果还不错,好东西自然不能独享,正所谓独乐乐不如众乐乐,这次就拿出来和大家分享一下吧。
下面是主要代码(插入到 functions.php 中):
- function Autofirst(){
- $db = Typecho_Db::get();
- $query = $db->select()->from(‘table.comments’)->where(‘authorId = ?’,’0′)->order(‘coid’,Typecho_Db::SORT_DESC)->limit(100);
- $result = $db->fetchAll($query);
- $arrUrl = array();
- $arrAuthor = array();
- foreach ($result as $value) {
- if($value[“url”]!==null){
- array_push($arrUrl,$value[“url”]);
- array_push($arrAuthor,$value[“author”]);
- }
- }
- $su=array_filter(array_merge(array_unique($arrUrl)));
- $sa=array_filter(array_merge(array_unique($arrAuthor)));
- $num=0;
- for($i=0;$i<count(array_unique($su));$i++){
- if($su[$i]!==“” && $num<16){
- $num+=1;
- $db1 = Typecho_Db::get();
- $query1 = $db1->select()->from(‘table.comments’)->where(‘url = ?’,$su[$i])->order(‘coid’,Typecho_Db::SORT_DESC)->limit(100);
- $result1 = $db1->fetchAll($query1);
- $arrAuthor1 = array();
- foreach ($result1 as $value) {
- array_push($arrAuthor1,$value[“author”]);
- }
- echo ‘<a href=“‘.$su[$i].'” rel=“external nofollow” class=“item col-lg-3 col-md-3 visible-lg visible-md” target=“_blank”><i class=“glyphicon glyphicon-leaf”></i> ‘.$arrAuthor1[0].'</a>’;
- }
- }
- }
这是调用代码和 css(如果你跟我一样,用的是 handsome 主题,就直接插入到 index.php 的”</header>”下面):
- <div class=“row autofirst visible-lg visible-md”>
- <p>
- <i class=“glyphicon glyphicon-th”></i> 每评论一次就会自动排在本栏目第一位
- </p>
- <?php Autofirst(100) ?>
- </div>
- <style>
- .autofirst{
- margin:20px 20px 5px 20px;
- padding:10px;
- box-shadow: 0 1px 8px rgba(0,0,0,0.12), 0 1px 8px rgba(0,0,0,0.24);
- background-color:white;
- border-radius:3px;
- }.item{
- padding:5px 0px;
- }
- </style>
上面的这两段代码中的 HTML 和 CSS 我是按照 handsome 主题制定的,使用其他主题的同学可以自己把 HTML 和 css 改一下。