Replace star ratings in Woocommerce using hooks

2019-08-01 02:25发布

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;
}

2条回答
我命由我不由天
2楼-- · 2019-08-01 03:02

woocommerce_product_get_rating_html would be the filter you want, but I don't think even that is broad enough for what you're looking to do. You're going to have to override the rating.php templates to get all of that changed.

woocommerce/templates/single-product/rating.php if you're doing it on the single product page. if you're doing it in the loop then above filter should work fine, but here's the template location for that anyways woocommerce/templates/loop/rating.php

查看更多
放我归山
3楼-- · 2019-08-01 03:19

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.

查看更多
登录 后发表回答