在WooCommerce中用if else实现评论计数显示或自定义文本输出
Modify WooCommerce Review Display with Conditional Logic
Hey there! Let's adjust your WooCommerce code to add that if/else logic you're needing. The goal is to show the review count link when there are existing reviews, and display a custom string when there aren't any. Here's the modified code with clear conditional checks:
<?php if ( $rating_count >= 0 ) : ?> <?php echo wc_get_rating_html($average, $rating_count); ?> <?php if ( comments_open() ): ?> <?php // Conditional check for review count if ( $review_count > 0 ) : ?> <a href="<?php echo get_permalink() ?>#reviews" class="woocommerce-review-link" rel="nofollow"> (<?php printf( _n( '%s review', '%s reviews', $review_count, 'woocommerce' ), '<span class="count">' . esc_html( $review_count ) . '</span>' ); ?>) </a> <?php else : ?> <!-- Replace this text with your custom string --> <span class="woocommerce-no-reviews">No reviews yet</span> <?php endif; ?> <?php endif; ?> <?php endif; ?>
Key Changes Explained:
- Added a nested
if ( $review_count > 0 )check right inside your existingcomments_open()condition. This triggers the original review link only when there are actual reviews to show. - For the "no reviews" case, I added a span with a custom class (
woocommerce-no-reviews) so you can easily style it with CSS if needed. Replace the text inside the span with whatever custom string you want to display. - Updated the
_n()function to handle proper singular/plural wording ("1 review" vs "5 reviews")—this follows WooCommerce's built-in localization best practices. - Kept all existing security measures intact, like
esc_html()for escaping output andrel="nofollow"on the review link.
Bonus: Localize Your Custom String
If you need your custom text to be translatable (for multi-language stores), swap the static text with a localization function:
<span class="woocommerce-no-reviews"><?php _e( 'No reviews yet', 'woocommerce' ); ?></span>
This lets you add translations for the string via WooCommerce's translation system or a plugin like WPML.
内容的提问来源于stack exchange,提问作者Wilson Ellis
相关产品推荐
相关产品推荐

