How to get the rating value of each comment

I want to get the rating value for a single review comment to create a custom reviews display, for example if a user rates a product with 4 stars, i want to get just the number 4, without any html.

I know this value is stored in a variable like below. But i don’t know how to get it for each comment.

$rating = $product->get_average_rating()

Edit: With Maxin’s answer i’ve created a function to show the custom comment, all works except for the comment_meta “rating”.

global $comment;
function custom_comments() {  ?>
<div class="comment">
    <p><?php comment_author(); ?></p>
    <p><?php intval( get_comment_meta( $comment->comment_ID, 'rating', 
    true ) ); ?></p>
    <p><?php comment_date(); ?></p>
    <p><?php comment_text(); ?></p>
</div>

I’m calling the function like this.

$args = array (
'post_id' => $product_id
);    
$comments = get_comments($wp_list_comments( array( 
  'type' => 'comment',
  'callback' => 'custom_comments'
), $comments);

The rating meta is returning this error “Trying to get property of non-object” and zero. What could it be?

That worked:

$comments = get_comments(array(
  'post_id' => $product_id,
));
foreach($comments as $comment) {
  <div class="comment">
    <p><?php comment_author(); ?></p>
    <p><?php echo get_comment_meta( $comment->comment_ID, 'rating', true); ?
    ></p>
    <p><?php comment_date(); ?></p>
    <p><?php comment_text(); ?></p>
  </div>
}

Answer

Product reviews is a default comments in WordPress. And rating stored in meta fields. Use get_comment_meta().

If you have custom reviews – you should have custom comments query. For every comments – get post meta. Look into wp_commentsmeta table in your database.

Attribution
Source : Link , Question Author : Gabriel Souza , Answer Author : Maxim Sarandi

Leave a Comment