skip to Main Content

I’m building a WooCommerce website that has a custom review system. I want to show the same reviews for multiple products that are variations but have their own product page.

Still I want to be able to sort products based on their rating, so I want to programmatically update ‘_wc_average_rating’ whenever a custom review is placed. Also the rich data markup is using these fields to populate the rich data markup.

I’m using the following code to update the meta values.

update_post_meta( 13566, '_wc_review_count', 4);
update_post_meta( 13566, '_wc_rating_count', 4);
update_post_meta( 13566, '_wc_average_rating', 5.00); 

For the review and rating count it is working fine, but for the average rating it’s not working.

I tried different things, like:

update_post_meta( 13566, '_wc_average_rating', 5.00); 
update_post_meta( 13566, '_wc_average_rating', 5); 
update_post_meta( 13566, '_wc_average_rating', '5.00'); 

How can I update the _wc_average_rating meta field? Is there a function to do this?

Thanks so much!

2

Answers


  1. Chosen as BEST ANSWER

    My website is running WPML, and that plugin uses it's own 2 meta fields to sync rating/reviews across different languages. The meta fields are:

    _wcml_average_rating
    _wcml_review_count
    

    So to update the rating in a WPML website, you need to update all these fields:

    update_post_meta( $product->get_id(), '_wc_review_count', $count);
    update_post_meta( $product->get_id(), '_wc_rating_count', $count);
    update_post_meta( $product->get_id(), '_wcml_review_count', $count);
    update_post_meta( $product->get_id(), '_wcml_average_rating', $rating);
    update_post_meta( $product->get_id(), '_wc_average_rating', $rating);
    

  2. I’ve tried the following code to verify your approach, and on my site its totally working. My average rating for my product 249 gets changed to 2:

    add_action( 'init', function () {
        $product = wc_get_product( 249 );
        error_log( $product->get_average_rating( 'edit' ) );
        update_post_meta( $product->get_id(), '_wc_average_rating', 2.00 );
    } );
    

    If you check this image – my first rating set the average rating to 5 and I changed it with my code to 2:

    enter image description here

    So I really don’t know what’s not working on your site. I just can confirm that updating the average rating is possible the way I showed you.

    Maybe you can show me the place where you execute your code. Sometimes this may be the problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search