WordPress树形层级输出文章评论方法

由于WordPress自带的方法生成的评论列表太过于僵硬,我们有时候需要自定义的输出形式,官方给的函数就不够用了,这时候就需要自己做一个查询与输出的方法。

下面是前几天做主题时用到的方法,亲测可用。本来想偷懒百度一个来用的,找了好久都没找到。只好自己写一个,分享给大家咯。

代码比较少,直接贴。

function mo_comments_list($postid) {
   global $wpdb;
 $comments = $wpdb->get_results('SELECT * FROM  wp_comments WHERE comment_post_ID ='.$postid); 
 //echo  count($comments);
 foreach($comments as $comment){
if($comment->comment_parent==0){
getcomment_content($comment);
// echo "</br>";
getchaildcomment($comments ,$comment->comment_ID,5);
echo "</div>";
}
 }
}
function getcomment_content($comment){
echo '<div class="comment-item comment-'.$comment->comment_ID.'">'._get_the_avatar($user_id=$comment->user_id, $user_email=$comment->comment_author_email).'<div class="text">'.$comment->comment_content.'</div>';
echo '<footer><span class="user">'.$comment->comment_author.'</span><time>'.$comment->comment_date.'</time><a href="javascript:;" class="reply" etap="comment_reply" data-id="'.$comment->comment_ID.'">回复</a></footer>';
}
function getchaildcomment($comments,$comment_id,$limit){
if($limit>0){
foreach($comments as $comment){
if($comment->comment_parent==$comment_id){
echo '<div class="comment-item comment-'.$comment->comment_ID.'">'._get_the_avatar($user_id=$comment->user_id, $user_email=$comment->comment_author_email).'<div class="text">'.$comment->comment_content.'</div>';
echo '<footer><span class="user">'.$comment->comment_author.'</span><time>'.$comment->comment_date.'</time><a href="javascript:;" class="reply" etap="comment_reply" data-id="'.$comment->comment_ID.'">回复</a></footer>';
getchaildcomment($comments,$comment->comment_ID,$limit-1);
echo '</div>';
}
}
}else{
}
}

将上述代码复制到主题目录下的function.php文件中,即可在WordPress目录文件中调用。

还是说明一下这个方法的原理。

首先使用了一个数据库查询,查询了评论数据表wp_comments里的评论数据。然后取出对应文章id的所有评论,再对所有评论进行遍历。在遍历所有评论时,使用到了一个递归函数输出评论下的回复。

使用方法:

直接调用mo_comments_list方法,传入文章id即可。方法getcomment_content是用来获取父级评论的方法,需要传入数据库查询内容。在里面调用了getchaildcomment方法获取评论回复,该方法需要三个参数,第一个是数据库查询内容,第二个是父级评论id,第三个是需要递归多少次,我这里只递归了5次,如果你的评论嵌套的比较多,可以自定义这里的5.