简体   繁体   中英

Finding sum of ACF custom field value for comments

I have created a few custom fields for comments to allow reviews on a Wordpress site built for listing hotels with user reviews as comments. One of these custom fields is a 'star_rating' field. I need to find a way to fetch the total sum of all values in order to find the average 'star_rating' value for each post to be displayed in search results and on the listing profile.

I have been trying for a long time to find the total sum for the star_rating field values. I have last used the following code but it does not work although I cannot see why. Any help would be much appreciated.

$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;

Many thanks in advance.

If you are using ACF custom field plugin, try to use get_field() function. You can't access your custom field $comment->star_rating like this.

尝试在以下自定义查询中获取星级:

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM