如何在 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”等
我可以使用什么代码在循环外显示用户的评论数?