PHP Snippet: Woocommerce Reviews as Shortcode

Are you using the Flatsome theme for your WooCommerce website and want to display product reviews in a shortcode?

With this tutorial, you’ll learn how to easily add a custom PHP snippet to your Flatsome theme and create a shortcode to showcase the reviews of the current product. By following these step-by-step instructions, you’ll be able to enhance your product pages and provide valuable social proof to your customers. Let’s get started!

Reviews retrieved by a shortcode
// Return a review shortcode of a Woocommerce product

add_shortcode( 'product_reviews', 'display_product_reviews_shortcode' );

function display_product_reviews_shortcode( $atts ) {
    global $post;
    
    if ( empty( $atts ) ) return '';
    
    $product_id = $post->ID;
    
    $comments = get_comments( 'post_id=' . $product_id );
    
    if ( ! $comments ) return '';
    
    $html = '<div class="woocommerce-tabs"><div id="reviews"><ol class="commentlist">';
    
    foreach ( $comments as $comment ) {
        $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
        $html .= '<li class="review">';
        $html .= get_avatar( $comment, '40' );
        $html .= '<div class="comment-text">';
        if ( $rating ) $html .= wc_get_rating_html( $rating );
        $html .= '<p class="meta"><strong class="woocommerce-review__author">';
        $html .= get_comment_author( $comment );
        $html .= '</strong> - <time class="woocommerce-review__published-date" datetime="' . get_comment_date( 'c', $comment ) . '">' . get_comment_date( '', $comment ) . '</time></p>';
        $html .= '<div class="description">';
        $html .= $comment->comment_content;
        $html .= '</div></div>';
        $html .= '</li>';
    }
    
    $html .= '</ol></div></div>';
    
    return $html;
}

The provided PHP snippet adds a shortcode that will display the product reviews specific to the current product being viewed. The shortcode can be added to any page or post content using the [product_reviews id=""] shortcode.

Please note that it’s important to always make a backup of your theme files before making any changes.

Last updated