Replace star ratings in Woocommerce using hooks

只愿长相守 提交于 2019-12-24 08:07:26

问题


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.

Code:

add_filter( 'woocommerce_get_star_rating_html', 'replace_star_ratings' );

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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/53890378/replace-star-ratings-in-woocommerce-using-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!