20150211003648

這個功能網上早已經有人實現了,程式碼使用的人數也不少,但是缺點非常明顯,就是每條評論都要查詢一次資料庫,如果你這個頁面有 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{ … }