仅显示作者的最新评论

时间:2014-02-01 08:26:15

标签: wordpress comments

您好我有代码在我的模板中显示评论列表。我的问题可能只显示作者的最新评论。示例:如果作者B在同一篇文章中发表了3条评论,我想显示作者B的最新评论,并排除/隐藏作者B发表的其他评论。

这是我的代码:

    <table class="table table-striped">  
        <thead class="btn-primary bottom-margin">   
            <tr>
                <th>Form ID</th>
                <th>Subject</th>  
                <th>Author</th>
                <th>Date</th>
            </tr>  
        </thead>

        <tbody>

            <?php  $args = array(
                'status' => 'approve',
                'number' => 0,
                'order' => 'DESC'
            );
                $comments = get_comments($args);
                foreach($comments as $comment) : $count++;?>

            <?php  $post_args = array(
                'post_type' => 'ticket_system',
                'p' => $comment->comment_post_ID,
                'posts_per_page' => 50
                );

                $posts = get_posts($post_args);
                foreach($posts as $post) : setup_postdata($post);?>

                    <tr>
                        <td class="col-md-2 flags"><?php echo get_post_meta($post->ID, "idticket",$single = true); ?></td>
                        <td class="col-md-6 flags"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title();?></a></td>  
                        <td class="col-md-2 flags"><?php echo $comment->comment_author;?></td>
                        <td class="col-md-2 flags"><?php echo $comment->comment_date;?></td>
                    </tr> 


            <?php  endforeach;
            endforeach; ?>      

        </tbody>
    </table>

1 个答案:

答案 0 :(得分:1)

您必须使用“GROUP BY”子句来获取每位作者的最新评论,而“get_comments()”函数不会为“group by”提供参数。 (列出了支持的参数here)。

您必须通过get_results()函数查询注释表并传递MySql查询,因此代码如下所示:

$table_prefix = $wpdb->prefix; // Get the WP table prefix in your database
$table_name = "comments"; // Table name we need to query
$table = $table_prefix . $table_name; // prefixing the table name
$comments = $wpdb->get_results("SELECT * FROM (SELECT * FROM " . $table . " where comment_approved=1  order by comment_date desc)c group by comment_author order by comment_date desc");

现在在$ comments中你有每个作者的最新评论,你可以随意循环。

请注意我按照作者姓名对评论进行分组,您可以为“comment_author_email”进行分组,或者通过“comment_author_IP”进行非常具体的分析。

我希望这会有所帮助。