admin管理员组

文章数量:1125410

I want to get the amount of reviews of a certain woocommerce product. I have this code but it gives me the total amount of reviews (so only the amount of reviews of that specific product).

function get_total_reviews_count(){
    return get_comments(array(
        'post_ID' =>'12345',
    'status'   => 'approve',
        'post_status' => 'publish',
        'count' => true
    ));
}
add_shortcode('reviews_count', 'get_total_reviews_count');

Hope you guys can help me adjust the code so that I will only see the amount of reviews of product 12345.

I want to get the amount of reviews of a certain woocommerce product. I have this code but it gives me the total amount of reviews (so only the amount of reviews of that specific product).

function get_total_reviews_count(){
    return get_comments(array(
        'post_ID' =>'12345',
    'status'   => 'approve',
        'post_status' => 'publish',
        'count' => true
    ));
}
add_shortcode('reviews_count', 'get_total_reviews_count');

Hope you guys can help me adjust the code so that I will only see the amount of reviews of product 12345.

Share Improve this question edited Sep 3, 2020 at 12:15 Christine Cooper 8,8777 gold badges60 silver badges93 bronze badges asked Sep 3, 2020 at 12:14 BasBas 11 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

WooCommerce provides a function for this. You should not need to query the comments and count them:

add_shortcode(
    'reviews_count',
    function() {
        // Make sure we're on a Product.
        if ( function_exists( 'is_product' ) && is_product() ) {
            // Get a WC_Product object for the current product.
            $product = wc_get_product( get_queried_object_id() );
            // Return the review count.
            return $product->get_review_count();
        }
    }
);

If you want to display the reviews count for a specific product you can use:

add_shortcode(
    'reviews_count',
    function() {
        if ( function_exists( 'wc_get_product' ) ) {
            // Get a WC_Product object for the product.
            $product = wc_get_product( 12345 );
            // Return the review count.
            return $product->get_review_count();
        }
    }
);

If you want to be able to pass the product ID to the shortcode (like this: [reviews_count id="12345"]), you can use:

add_shortcode(
    'reviews_count',
    function( $atts ) {
        // Make sure an ID was passed,
        if ( ! empty( $atts['id'] && function_exists( 'wc_get_product' ) ) {
            // Get a WC_Product object for the product.
            $product = wc_get_product( (int) $atts['id'] );
            // Return the review count.
            return $product->get_review_count();
        }
    }
);

本文标签: commentsReview count per product