Lars
Lars

Reputation: 11

Create WooCommerce shortcode to display product reviews on single product page

I'm trying to generate a shortcode that gives me the option to display the reviews/ratings of a WooCommerce product anywhere on the single product page.

So far, the reviews are displayed by default in the reviews tab. I have already deactivated this tab. So I want to list the reviews further down below the product description where I add the shortcode.

Important: I don't want to enter the id of the product manually in the short code, it should be automatically dragged from the current showing product.

Here is my code:

add_shortcode( 'product_reviews', 'display_product_reviews' );
function display_product_reviews( $atts ){
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
    ), $atts, 'product_reviews' );

    global $product;

    if ( ! is_a( $product, 'WC_Product') )
        $product = wc_get_product($atts['id']);

    $comments = get_comments( 'post_id=' . $atts['id'] );
    
   if ( ! $comments ) return '';
    
   $html .= '<div class="abc"><div id="reviews"><ol class="list">';
    
   foreach ( $comments as $comment ) { 
      $rating = intval( get_comment_meta( $comment->comment_ID, 'rating', true ) );
      $html .= '<li class="review">';
      $html .= get_avatar( $comment, '60' );
      $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></p>';
      $html .= '<div class="description">';
      $html .= $comment->comment_content;
      $html .= '</div></div>';
      $html .= '</li>';
   }
    
   $html .= '</ol></div></div>';
    
   return $html;
}

On single product page, I add this shortcode: [product_reviews]

Unfortunately, something is not working here...

I tried different code variations without success.

Upvotes: 1

Views: 537

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

You can try to use the following improved code version of your shortcode:

add_shortcode( 'product_reviews', 'display_product_reviews' );
function display_product_reviews( $atts ){
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
    ), $atts, 'product_reviews' );

    global $product, $post;

    if ( ! is_a( $product, 'WC_Product') ) {
        $product = wc_get_product($atts['id']);
        $post    = get_post($atts['id']);
    }
    
    ob_start(); // start buffering

    comments_template();
    
    return ob_get_clean(); // Return buffered content
}

Code goes in function.php file of your child theme (or in a plugin). Tested and works.


Important note:

If you are using a block theme and If you use single product Blocks, maybe you should use the product reviews Block, instead of a custom shortcode.

Upvotes: 1

Related Questions