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