• 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 on on the 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.

Viewing 1 replies (of 1 total)
  • Amit Biswas

    (@amitbiswas06)

    Dear cdbrosnan,

    I saw your question today while searching for similar issues. Fortunately I have resolved the issue for one of my project. As described in the question, you are using a ACF field star_rating in comments to grab float values.

    To get values from comments, you need to use get_field function for ACF fields. Here you can find how – https://www.advancedcustomfields.com/resources/get-values-comment/

    So in this case,

    Your code should be like this –

    global $post; // if you are using this outside the WP loop
    $ratings_sum = "";
    $comment_array = get_approved_comments( $post->ID ); // only approved comment from a post
    
       // foreach loop to get rating values of each comment
       foreach( $comment_array as $comment ) {
    
          // 'star_rating' is your ACF field ID. Storing it in a variable $star_value
          $star_value = get_field('star_rating', $comment);
    
          // Addition
          $ratings_sum += $star_value;
    
       }
    
    echo $ratings_sum;

    Let me know if that works for you.

    Thanks,
    Amit

Viewing 1 replies (of 1 total)
  • The topic ‘Finding sum of ACF custom field value for comments’ is closed to new replies.