前几天做主题时遇到这个问题,由于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.
安装KB5014697补丁以后开启热点无法上网怎么办?
Windows 11 的最新星期二补丁KB5014697更...(627 )人阅读时间:2025-11-25
Win11本地安全策略在哪里?Win11添加IP 安全策略的
IP安全策略是一个给予通讯分析的策略,当我们配置好IP安全...(948 )人阅读时间:2025-11-25
Win11字体显示不全如何解决?Win11字体显示不全解决方
Win11系统是当前最好用的系统之一,在给用户带来全新界面...(752 )人阅读时间:2025-11-25
Win11怎么创建虚拟磁盘?Win11创建虚拟磁盘的方法
虚拟磁盘就是用内存中虚拟出一个或者多个磁盘的技术。和虚拟内...(607 )人阅读时间:2025-11-25