Search code examples
phpwordpresswoocommerceproductrating

Add stars rating to rating menu item title in Woocommerce product tab section


I'm trying to add the 5 stars rating for a product in Woocommerce next to the rating tab name.

1

I added in my function.php file this code :

add_filter( 'woocommerce_product_tabs', 'woo_rename_tabs', 98 );
function woo_rename_tabs( $tabs ) {

    $tabs['reviews']['title'] = __('Ratings');

    return $tabs;

}

This give me the chance to change the name of the tab. It's not exactly what I want to do but I thought I could use this function and add the 5 stars rating next to the reviews tab title by adding $average to it

$average      = $product->get_average_rating();

So I'm stuck there. I don't know how to add $average next to the title. I tried this :

$tabs['reviews']['title'] = __('Ratings', $average);

But doesn't work. I'm still a newby with PHP. If you can point me into the right direction, I will appreciate.


Solution

  • It's possible to add stars rating to reviews menu item label using the following (but some CSS styling will be necessary to get something clean and inline):

    add_filter( 'woocommerce_product_reviews_tab_title', 'add_stars_to_reviews_tab_item', 98 );
    function add_stars_to_reviews_tab_item( $title ) {
        global $product;
    
        $average_rating = $product->get_average_rating();
    
        if( ! empty($average_rating) && $average_rating > 0 )
            $title = '<div>' . $title . '</div>
            <div class="stars">' . wc_get_rating_html($average_rating) . '</div>';
    
        return $title;
    }
    

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

    screenshot