查找评论的 ACF 自定义字段值的总和

Finding sum of ACF custom field value for comments

我已经为评论创建了一些自定义字段,以允许在 Wordpress 网站上进行评论,该网站是为将用户评论作为评论列出的酒店而构建的。这些自定义字段之一是 'star_rating' 字段。我需要找到一种方法来获取所有值的总和,以便找到要在搜索结果和列表配置文件中显示的每个 post 的平均 'star_rating' 值。

我已经尝试了很长时间才能找到 star_rating 字段值的总和。我上次使用了以下代码,但它不起作用,尽管我不明白为什么。任何帮助将不胜感激。

$ratings_sum = 0;
// Arguments for the query
$args = array();
// The comment query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// The comment loop
if ( !empty( $comments ) ) {
    foreach ( $comments as $comment ) {
        $ratings_sum+= $comment->star_rating;
    }
} else {
    // echo 'No comments found.';
}
echo $ratings_sum;

非常感谢。

尝试使用以下自定义查询获取星级:

SELECT SUM(meta_value) FROM wp_commentmeta WHERE comment_id IN (SELECT comment_ID FROM wp_comments WHERE comment_post_ID = '//your post id') and meta_key='star_rating';

如果您使用的是ACF自定义字段插件,请尝试使用get_field()功能。您无法像这样访问您的自定义字段 $comment->star_rating