2 回答

TA貢獻1851條經驗 獲得超4個贊
要顯示可變產品變體中選定的產品價格,需要 jQuery。因此,以下短代碼將處理所有產品類型,包括可變產品及其價格變化:
add_shortcode( 'product_price', 'display_formatted_product_price' );
function display_formatted_product_price( $atts ) {
extract(shortcode_atts( array(
'id' => null
), $atts, 'product_price' ) );
global $product;
if( ! empty($id) || ! is_a($product, 'WC_Product') ) {
$product = wc_get_product( empty($id) ? get_the_id() : $id );
}
$price_html = $product->get_price_html();
// Others product types than variable
if ( ! $product->is_type('variable') ) {
return '<span class="product-price">' . $price_html . '</span>';
}
// For variable products
else {
ob_start();
?>
<script type="text/javascript">
jQuery( function($){
var p = '<?php echo $price_html; ?>', s = 'span.product-price';
$( 'form.variations_form.cart' ).on('show_variation', function(event, data) {
$(s).html(data.price_html); // Display the selected variation price
});
$( 'form.variations_form.cart' ).on('hide_variation', function() {
$(s).html(p); // Display the variable product price range
});
});
</script>
<?php
return ob_get_clean() . '<span class="product-price">' . $price_html . '</span>';
}
}
代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。
用途:
[product_price]在 php 代碼中使用or echo do_shortcode('[product_price]')。
您還可以定義產品 ID,例如(例如產品 id 37):[product_price id="37"]

TA貢獻1827條經驗 獲得超4個贊
我對一個問題很頭疼:如果產品變體都具有相同的價格,則price_html將返回空(。我使用上面 github 轉換中找到的過濾器解決了這個問題:
add_filter(?'woocommerce_show_variation_price',?'__return_true');
- 2 回答
- 0 關注
- 130 瀏覽
添加回答
舉報