WooCommerce提供a function 为了这个。您不需要查询并统计评论:
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();
}
}
);
如果要显示特定产品的评论计数,可以使用:
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();
}
}
);
如果希望能够将产品ID传递给快捷码(如下所示:
[reviews_count id="12345"]
), 您可以使用:
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();
}
}
);