Nec
Nec

Reputation: 178

Woocommerce latest review

I am trying to get the latest comment / review on any product on my test page, so far i am treating it as a post, and got something like this :

<?php
    $args = array ('post_type' => 'product');
    $comments = get_comments( $args );
    wp_list_comments( array( 'callback' => 'woocommerce_comments' ), $comments);
?>

<?php get_comments( $args ); ?>

Any help is much appreciated.

Upvotes: 0

Views: 1499

Answers (2)

Yazmin
Yazmin

Reputation: 1194

This is what I did to get the latest comment for a product:

function display_product_review() {
    global $product;

    $comments = get_approved_comments( $product->id );

    $product_link = '/product/' . $product->post->post_name . "/#tab-reviews/";

    if ( !empty ($comments) ) {
        echo $comments[0]->comment_content . '<br><a href="'. $product_link . '">Read more reviews...</a>';
    } else {
        echo "There are no reviews for this product yet. Would you like to <a href='" . $product_link ."'>add your own review</a>?";       
    }
}

The only downside is that get_approved_comments only has one parameter, which is the post_id, so it does pull all reviews made for the product. It may not be the cleanest solution, but it did work for me.

Upvotes: 1

Rohil_PHPBeginner
Rohil_PHPBeginner

Reputation: 6080

Try this:

$number_of_reviews = 10; //How many reviews you want to retrieve
$reviews = get_comments( array( 'number' => $number_of_reviews, 'status' => 'approve', 'post_status' => 'publish', 'post_type' => 'product' ) );

echo "<ul>";
foreach ( (array) $reviews as $review ) {
    $_product = WC_get_product( $review->comment_post_ID );
    $rating = intval( get_comment_meta( $review->comment_ID, 'rating', true ) );

    echo '<li style="list-style:none"><a href="' . esc_url( get_comment_link( $review->comment_ID ) ) . '">';
        echo $_product->get_title() . '</a>  ';
        for($i=0;$i<$rating;$i++){
            echo "<span style='color:grey'>&#9733</span>";
        }
        echo "<p>".$review->comment_content."    -   ".get_comment_author($review->comment_ID)."</p>";

    echo '</li><br><br>';
}
echo "</ul>";

Note: You can always modify your code as per your need and CSS as well.

Upvotes: 2

Related Questions