questions

Custom function that get product reviews count in WooCommerce

Rate this post

I’m trying to make a function that get the count of product reviews in WooCommerce product page.

I need to use it in another function in a logical operation … Can’t figure out whats wrong.

function reviews_count() {
    $id = $product->get_id();
    $product = wc_get_product($id);
    $count = $product->get_review_count();
    return $count;
}

 

✔️Solution:

Try the following instead (for single product_pages):

function reviews_count() {
    global $product;

    if ( ! is_a( $product, 'WC_Product' ) ) {
        $product = wc_get_product( get_the_ID() );
    }
    return $product->get_review_count();
}

Or you can also add the product Id as function argument (to use it in another function) like:

function reviews_count( $product_id ) {
    $product = wc_get_product( $product_id );

    return $product->get_review_count();
}

So in your other function, you will be able to pass the product Id a bit like:

function my_other_function() {
    global $product;

    $count = reviews_count( $product->get_id() );
}

Leave a Reply

Your email address will not be published.

Back to top button