Nik*_*thu 1 php wordpress product woocommerce price
我创建了这段代码,可以在网站上的任何页面上显示价格,该价格由 woocommerce 控制。
add_shortcode( 'hhs_product_price', 'hhs_woo_product_price_shortcode' );
function hhs_woo_product_price_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => null
), $atts, 'hhs_product_price' );
if ( empty( $atts[ 'id' ] ) ) {
return '';
}
$product = wc_get_product( $atts['id'] );
if ( ! $product ) {
return '';
}
return $product->get_price_html();
}
Run Code Online (Sandbox Code Playgroud)
我想做的是修改代码,以便客户选择具有变体的产品。然后价格发生变化以显示变化价格。例如,现在如果一个人选择一种产品,在本例中是酊剂瓶,价格变化与瓶子的尺寸有关。在产品页面上,他们看到以下内容:-
产品(酊剂) $30 - $50
他们可以从下拉菜单中选择 10 毫克瓶装(30 美元)、15 毫克瓶装(40 美元)或 20 毫克瓶装(50 美元)。因此,如果一个人选择 20mg 选项,价格应显示 50 美元,而不是 30 - 50 美元
我已经在 stackoverflow 上看过各种有类似问题的帖子,但这些解决方案都不适合我
任何帮助将不胜感激。
谢谢
要显示可变产品变体中选定的产品价格,需要 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>';
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
用法:
[product_price]在 php 代码中使用or echo do_shortcode('[product_price]')。
您还可以定义产品 ID,例如(例如产品 id 37):[product_price id="37"]