Search code examples
phpwordpresswoocommercehook-woocommercerating

Replace star ratings in Woocommerce using hooks


when enabled, every woocommerce product has a star rating. I have some custom code that I would like to replace the current star rating in its entirety (Including the "# customer reviews" part.

Currently, the code I am using only appends to the star rating, rather than replace it fully. Below is the current result I am seeing, and the code I have added to functions.php. Thank you in advance.

enter image description here

Code:

add_filter( 'woocommerce_get_star_rating_html', 'replace_star_ratings' );

function replace_star_ratings( $variable ) {
    echo "XXX";
    return $variable;
}

Solution

  • To replace completely Stars rating on products without editing templates, use the following:

    // For single product pages
    add_action( 'woocommerce_single_product_summary', 'custom_rating_single_product_summary', 4 );
    function custom_rating_single_product_summary() {
        global $product;
    
        if ( $product->get_rating_count() > 0 ) {
            remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 );
            add_action( 'woocommerce_single_product_summary', 'replace_product_rating', 9 );
        }
    
    }
    
    // For Shop and archicves pages
    add_action( 'woocommerce_after_shop_loop_item_title', 'custom_rating_after_shop_loop_item_title', 4 );
    function custom_rating_after_shop_loop_item_title() {
        global $product;
    
        if ( $product->get_rating_count() > 0 ) {
            remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );
            add_action( 'woocommerce_after_shop_loop_item_title', 'replace_product_rating', 5 );
        }
    
    }
    
    // Content function
    function replace_product_rating() {
        global $product;
    
        $rating_count = $product->get_rating_count();
        $review_count = $product->get_review_count();
        $average      = $product->get_average_rating();
    
        echo '<div class="woocommerce-product-rating">'. __("XXX", "woocommerce") . '</div>';
    }
    

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