WordPress树形层级输出文章评论方法
发布时间:2025-10-19 15:13:58 本站作者 【 字体:大 中 小 】 浏览:6 次
前几天做主题时遇到这个问题,由于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.
上一篇:WordPress自动分页方法

office2010密钥,office2010激活密钥,office2010永久密钥激活码最新分享


office365激活密钥,小编分享2025最新office365激活码


office2018产品密钥,小编告诉你office2018怎么激活


怎么激活office2019最新版?office 2019激活秘钥+激活工具推荐

office2010密钥,office2010激活密钥,office2010永久密钥激活码最新分享

office365激活密钥,小编分享2025最新office365激活码

office2018产品密钥,小编告诉你office2018怎么激活

怎么激活office2019最新版?office 2019激活秘钥+激活工具推荐

Office2019 激活密钥, Office2019 怎么激活激活?

Office2016激活密钥专业增强版(神Key)Office2016永久激活密钥[2025.10更新]
![Office2016激活密钥专业增强版(神Key)Office2016永久激活密钥[2025.10更新]](/static/upload/image/20251020/1760945332659252.jpg)
office2016永久激活密钥从哪里找?永久激活office2016的方法,一步一步的详细教程来了

office2016怎么激活密钥?office2016怎么安装?今天一文讲清楚

Office2016最新激活密钥分享,office2016密钥永久激活码

office2010永久秘钥是多少 office2010序列号分享 附激活工具
