How can I edit the ratings output in woocommerce to remove the text and just how the stars without using css

1.4k Views Asked by At

I'm new to coding and wordpress/woocommerce and am trying to find a simple way to edit the output of wc_get_rating_html.

At the moment it outputs the following:

function wc_get_rating_html( $rating ) { 
    if ( $rating > 0 ) { 
        $rating_html = '<div class="star-rating" title="' . sprintf( esc_attr__( 'Rated %s out of 5', 'woocommerce' ), $rating ) . '">'; 
        $rating_html .= '<span style="width:' . ( ( $rating / 5 ) * 100 ) . '%"><strong class="rating">' . $rating . '</strong> ' . esc_html__( 'out of 5', 'woocommerce' ) . '</span>'; 
        $rating_html .= '</div>'; 
    } else { 
        $rating_html = ''; 
    } 
    return apply_filters( 'woocommerce_product_get_rating_html', $rating_html, $rating ); 
} 

I simply want to output the star rating and not the text that goes before and after. Any suggestions on how i can do this as i obv cant edit the template file. thanks

1

There are 1 best solutions below

0
T Paone On

Wordpress utilizes filters which allow you to replace and/or modify the output of what the filter processes. Here is the full block for the wc_get_rating_html function:

function wc_get_rating_html( $rating, $count = 0 ) {
    $html = '';

    if ( 0 < $rating ) {
        /* translators: %s: rating */
        $label = sprintf( __( 'Rated %s out of 5', 'woocommerce' ), $rating );
        $html  = '<div class="star-rating" role="img" aria-label="' . esc_attr( $label ) . '">' . wc_get_star_rating_html( $rating, $count ) . '</div>';
    }

    return apply_filters( 'woocommerce_product_get_rating_html', $html, $rating, $count );
}

In your example, woocommerce_product_get_rating_html is the filter name and takes three arguments:

$rating_html which represents the output which the user sees

$rating which is the numerical rating

$count which is the total number of ratings.

If you wish to replace the output, you'll need to hook into the filter woocommerce_product_get_rating_html with a function that will return the modified content. You'll definitely need to review Hooks & Filters and how they work in Wordpress if you are not familiar with utilizing hooks and filters in Wordpress.