Search code examples
wordpresswoocommercehook-woocommerce

How to display reviews on an under product title in cart of woocommerce?


I am trying to add the number of reviews and the star rating reviews on the product. I want to achieve something like this. enter image description here

The snippet I use to achieve it(not exactly but similar) is this

add_filter('woocommerce_cart_item_name', 'custom_item_display_on_cart', 10, 3);

function custom_item_display_on_cart($name, $cart_item, $item_key){
$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
$thumbnail = $_product->get_image();
$price = $_product->get_price_html(); 
$rating = woocommerce_review_display_rating();

$product_variation = '';
if(!empty($cart_item['variation_id']) && $cart_item['variation_id'] != 0 ){
   if(is_array($cart_item['variation']) && !empty($cart_item['variation'])){
      foreach ($cart_item['variation'] as $key => $value) {
         $product_variation .= ''.ucfirst(str_replace('attribute_pa_', '', $key)).' : '.ucfirst($value);
    }
}
}
    echo '<div class="product-item-wrapper"> '. '<div class="product-thumbnail-wrapper">' . $thumbnail. '</div>' . '<div class="item-wrapper">' . '<div class="product-name">' . $name . '</div>' . '<div class="product-variation">' . $product_variation . '</div>' .'<div class="product-price-item">' . $price . '</div>'. '</div>' . ' </div>' .$rating; 

This is the result of the snippet that I used enter image description here

I am close to achieving it but the only problem I am facing is the start rating reviews and the number of reviews. I tried using woocommerce_review_display_rating(); but it's not showing anything.

Thank you in advance!


Solution

  • You can use the woocommerce_after_cart_item_name action hook to display reviews below the title. code will go in your active theme functions.php file.

    add_filter('woocommerce_after_cart_item_name', 'woocommerce_after_cart_item_name', 10, 2);
    function woocommerce_after_cart_item_name( $cart_item, $cart_item_key  ){
        $product      = wc_get_product( $cart_item['product_id'] );
        $rating_count = $product->get_rating_count();
        $review_count = $product->get_review_count();
        $average      = $product->get_average_rating();
        if ( $rating_count > 0 ) : ?>
            <div class="woocommerce-product-rating">
                <?php echo wc_get_rating_html( $average, $rating_count ); // WPCS: XSS ok. ?>
                <div class="count"><?php echo esc_html( $review_count ); ?> Reviews</div>
            </div>
        <?php endif;
    }
    

    Tested and Works

    enter image description here