当前位置:K88软件开发文章中心编程语言PHPPHP01 → 文章内容

WordPress 评论等级高性能版

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-4 8:22:48

-->

这个功能网上早已经有人实现了,代码使用的人数也不少,但是缺点非常明显,就是每条评论都要查询一次数据库,如果你这个页面有100条评论的话就要查询100次数据库,不得不说性能非常不给力。解决方法就是一次把所有的评论都取出,然后已邮箱为键值封装成一个大数组,读取评论数的时候只需要在这个数组中取值就可以了。如果你的评论数超级多,还可以把封装的数组缓存起来,一般人的评论数都不是很多,这里就先不介绍缓存方法了。

实现方法

下面的代码直接加入到functions.php中

/* Globals */
global $total_comments;
add_action(“init”,”comments_globals”);

function comments_globals(){
global $total_comments;
$total_comments = get_total_commtents_num();
}

/* Return a big array */

function get_total_commtents_num() {
$array = array();
$comments = get_comments( array(‘status’ => ‘approve’) );
$admin_mail = get_option(‘admin_email’);
foreach($comments as $comment){
$email = $comment->comment_author_email;
if($email!=”” && $email!=$admin_mail){ // 排除邮箱
$array[$email] +=1;
}
}
return $array;
}

/* Return level */

function comment_level($email){

$num = $GLOBALS[“total_comments”][$email];
if($num > 0 && $num < 200){
$level = ‘<span title=”‘.ceil( $num/20 ) .’级,距离下一级还有条’ . ( 20 – $num%20 ) . ‘评论” class=”user-level-‘.ceil( $num/20 ) .’ user-level”>’.ceil( $num/20 ) .’级</span>’;
}else{
$level = ‘<span title=”满级” class=”user-level-top user-level”>满级</span>’;
}
return $level;
}

/* Hook */

function comment_level_hook($text) {
global $comment;
return $text.comment_level($comment->comment_author_email,20,10);
}
add_filter(‘get_comment_author_link’, ‘comment_level_hook’, 6);

参数调整

找到代码中的

comment_level($comment->comment_author_email,20,10)

为了调用简单,我做成了等级是线性增长的,后面个参数一个是每级评论数量,和最高等级。默认为每级20条评论,最高等级为10级。调整只需要修改这两个参数即可。

参考CSS 写法

如果希望增加CSS样式,只需给user-level-*定义即可,比如你最高级是10级,那么需要从user-level-1到user-level-10分别定义样式。user-level-top满级样式。下面代码为CSS 书写方法,不能直接使用。

.user-level{margin-left:5px}
.user-level-1{ … }
.user-level-2{ … }
…..
.user-level-10{ … }
.user-level-top{ … }

该文章由WP-AutoPost插件自动采集发布

原文地址:http://www.59iwp.com/436.html


WordPress 评论等级高性能版