如何用WooCommerce原生短代码/PHP显示可变产品当前价格?
Hey there! Let's sort out this variable product pricing issue you're hitting with WooCommerce. The Booster shortcodes showing $0 when no variation is selected makes sense—they’re probably pulling the price of an unselected (non-existent) variant. Instead, we can use native WooCommerce functions to display the full price range, no extra plugins needed.
Option 1: Custom Shortcode (Easy to Use in Page Builders/Text Blocks)
Add this code to your child theme’s functions.php file, or use a custom code snippet plugin (like Code Snippets) to avoid losing changes when your theme updates:
add_shortcode('wc_variable_price_range', 'display_variable_product_price_range'); function display_variable_product_price_range($atts) { // Set default product ID to current post if not specified $atts = shortcode_atts(array( 'id' => get_the_ID(), ), $atts, 'wc_variable_price_range'); $product = wc_get_product($atts['id']); // Return empty if product doesn't exist or isn't variable if (!$product || !$product->is_type('variable')) { return $product ? wc_price($product->get_price()) : ''; } // Get min/max variation prices (formatted with currency) $min_price = wc_price($product->get_variation_price('min', true)); $max_price = wc_price($product->get_variation_price('max', true)); // If all variants have the same price, show single price if ($min_price === $max_price) { return $min_price; } else { // Return formatted price range return sprintf('%s - %s', $min_price, $max_price); } }
Now you can use the shortcode [wc_variable_price_range] anywhere on your product page. For your desired message, just write:
本产品价格范围为[wc_variable_price_range],请选择选项查看精准定价
Option 2: PHP Code for Theme Template Edits
If you want to hardcode this directly into your product template (e.g., single-product/price.php), use this snippet:
global $product; if ($product->is_type('variable')) { $min_price = wc_price($product->get_variation_price('min', true)); $max_price = wc_price($product->get_variation_price('max', true)); if ($min_price !== $max_price) { echo '<p class="price-range-notice">本产品价格范围为' . $min_price . ' - ' . $max_price . ',请选择选项查看精准定价</p>'; } else { // If all variants cost the same, adjust the message echo '<p class="price-range-notice">本产品价格为' . $min_price . ',请选择选项确认</p>'; } } else { // For simple products, show regular price echo '<p class="price-range-notice">本产品价格为' . wc_price($product->get_price()) . '</p>'; }
Quick Notes
- The
get_variation_pricefunction pulls the actual prices from all variants, so it works even when no variation is selected. - Always back up your theme files before editing
functions.php, or use a child theme to preserve changes through theme updates.
内容的提问来源于stack exchange,提问作者TomJones999

