在循环之外显示用户的总评论计数

时间:2012-09-14 作者:Amanda Bynes

如何在循环外显示用户的总评论数?

我使用此代码显示注释计数inside the loop:

    <?php
    global $wpdb;
    $user_id = $post->post_author;
    $where = \'WHERE comment_approved = 1 AND user_id = \' . $user_id ;
    $comment_count = $wpdb->get_var(
        "SELECT COUNT( * ) AS total
    FROM {$wpdb->comments}
    {$where}
");
    echo \'Comments: <strong>\' . $comment_count . \'</strong>\';
    ?>
这在循环中非常有效。为了使代码在循环之外工作,我改变了$user_id = $post->post_author;$user_id = get_the_author_meta( \'ID\' ); 但它没有起作用。

我最接近的代码是:

                            <?php
                            global $wpdb;
                            $where = \'WHERE comment_approved = 1 AND user_id <> 0\';
                            $comment_counts = (array) $wpdb->get_results("
                                SELECT user_id, COUNT( * ) AS total
                                FROM {$wpdb->comments}
                                {$where}
                                GROUP BY user_id
                                ", object);
                            foreach ( $comment_counts as $count ) {
                                $user = get_userdata($count->user_id);
                                echo \'Comments: \' . $count->total . \'
                                \';
                            }
                            ?>
然而,这回应了所有用户的评论计数,如:“评论:28条评论:11条评论:55”等

我可以使用什么代码show the user\'s comment count outside the loop?

1 个回复
SO网友:Lars Koudal

您或多或少已经掌握了代码,只需稍微更改代码即可。

您没有提到如何获取用户id,但是如果您有要检查的用户id,那么在循环之外很容易做到。

下面是一个简单的示例:

$userid=1;
$comment_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) AS total FROM $wpdb->comments WHERE comment_approved = 1 AND user_id = %s", $userid ) );
echo "Number of comments for user $userid is $comment_count";
注意:查询中显示“comment\\u approved=1”的部分仅统计已批准的注释,如果要包括未批准的注释,请忽略该部分。

结束