如何在循环之外显示用户的评论总数?
我使用此代码在循环内显示注释计数:
<?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条"等
我可以使用什么代码在循环外显示用户的评论计数?
试着让一些事情变得更全局,并以不同的方式获取用户数据。
<?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(); ?>
我知道这个主题很老,但我只想删除一个片段,它更适合:
<?php
$args = array(
'post_id' => 1, // use post_id, not post_ID
'count' => true //return only the count
);
$comments = get_comments($args);
echo $comments
?>
其中"post_id"可以是"user_id"
如果您正在查看每个用户的个人资料,则应该使用WHERE comment_author_email = "' . get_comment_author_email() . '"
来获取每个用户的评论。。。@SMacFadyen的代码将只为登录用户提供评论计数。
此外,第二个函数不起作用。
试试这个
$post= get_post($id=5);
$comment_count = $post->comment_count;
$count = get_comments(array(
'user_id' => 1,
'count' => true, // return comment count instead of comments
));
echo $count;
作为一个函数,传递$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
));
}