如何在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”等
我可以使用哪些代码在循环外显示用户的评论数?
答案 0 :(得分:4)
尝试使一些事情更加全局化并以不同方式获取用户数据。
<?php
global $wpdb, $post, $current_user;
get_currentuserinfo();
$userId = $current_user->ID;
$where = 'WHERE comment_approved = 1 AND user_id = ' . $userId ;
$comment_count = $wpdb->get_var("SELECT COUNT( * ) AS total
FROM {$wpdb->comments}
{$where}");
echo 'Comments: <strong>' . $comment_count . '</strong>';
?>
或在functions.php中
<?
function commentCount() {
global $wpdb, $current_user;
get_currentuserinfo();
$userId = $current_user->ID;
$count = $wpdb->get_var('
SELECT COUNT(comment_ID)
FROM ' . $wpdb->comments. '
WHERE user_id = "' . $userId . '"');
echo $count . ' comments';
}
?>
要打电话
<?php commentCount(); ?>
答案 1 :(得分:0)
如果您正在观看他们的个人资料,您应该使用WHERE comment_author_email = "' . get_comment_author_email() . '"
来获取每个用户的评论... @SMacFadyen的代码将仅为登录用户提供评论计数。
此外,第二个功能不起作用。
答案 2 :(得分:0)
试试这个
$post= get_post($id=5);
$comment_count = $post->comment_count;
答案 3 :(得分:0)
我知道这个话题很老但只想删掉一个更合适的代码片段:
<?php
$args = array(
'post_id' => 1, // use post_id, not post_ID
'count' => true //return only the count
);
$comments = get_comments($args);
echo $comments
?>
在哪里&#39; post_id&#39;可以是&#39; user_id&#39;
答案 4 :(得分:0)
作为函数,传递$ user_id-还使用$ wpdb-> prepare()方法来格式化查询:
function get_comment_count( $user_id = null ) {
if ( is_null( $user_id ) ) { return 0; }
global $wpdb;
return $wpdb->get_var( $wpdb->prepare(
"
SELECT COUNT( * ) AS total
FROM {$wpdb->comments}
WHERE comment_approved = 1 AND user_id = '%d'
",
(int) $user_id
));
}