问题描述
我一直在寻找 Stack 的答案,但找不到(即使阅读 this 和 this)
这是我的麻烦:我想显示(或至少获取变量)woocommerce 变量产品的默认和选定价格。
系统:wordpress 5,6 + woocommerce
对于单一产品,我的代码运行良好,并且显示如下: Display for a single product with weight and price rewritten on right after quantity selector
代码如下:
global $woocommerce;
$productxyz = new WC_Product( get_the_ID() );
$priceproduct = $productxyz->get_regular_price();
$poidsproduct = $productxyz->get_weight();
// CODE FOR THE + AND - QUANTITY
var $ = jQuery;
$(document).ready(function(){
$('.decrement').click(function () {
$moninput = $(this).nextAll('input#Qte');
if( Number($moninput.val()) > $moninput.attr("min") ){
$moninput.val(Number($moninput.val()) - 1);
}else{
$moninput.val($moninput.attr("min"));
}
Update_Price();
event.preventDefault();
})
$('.increment').click(function () {
$moninput = $(this).nextAll('input#Qte');
$moninput.val(Number($moninput.val()) + 1);
Update_Price();
event.preventDefault();
})
$('#btn-cady').click(function () {
$('[name="add-to-cart"]').click();
event.preventDefault();
})
// CODE FOR THE TEXT disPLAYED ON THE RIGHT OF THE QUANTITY SELECTOR
function Update_Price(){
if($('input#Qte').attr('price') > 0){
$total = parseFloat($('input#Qte').val()) * $('input#Qte').attr('price');
$qtyactuelle = parseFloat($('input#Qte').val());
$('input[name="quantity"]').val($('input#Qte').val());
console.log($total);
if( $qtyactuelle < 2){
$('.Qtotal h4').html("<font color='#401816'>pack soit " +($('input#Qte').attr('weight')*parseFloat($('input#Qte').val()))+"g |</font> "+parseFloat($total).toFixed(2)+" €");
}
if($qtyactuelle > 1){
$('.Qtotal h4').html("<font color='#401816'>packs soit " +($('input#Qte').attr('weight')*parseFloat($('input#Qte').val()))+"g |</font> "+parseFloat($total).toFixed(2)+" €");
}
}
}
Update_Price();
});
但是对于变体产品...我为展示我的结果感到羞耻,因为当它显示良好时,功能不起作用。并且功能正常时,显示非常糟糕 Code result for variation product
我尝试使用 get_available_variations() 以及以下 foreach 但...
foreach( $product->get_available_variations() as $variation ){
$found = true;
// Loop through variation attributes
foreach( $variation['attributes'] as $key => $value ){
$taxonomy = str_replace( 'attribute_','',$key );
// Searching for a matching variation as default
if( isset($default_attributes[$taxonomy]) && $default_attributes[$taxonomy] != $value ){
$found = false;
break;
}
}
// If we get the default variation
if( $found ) {
$default_variaton = $variation;
break;
}
有没有人知道如何开发它?感觉无语了。
提前,非常感谢!!!
解决方法
在 WooCommerce 可变产品页面上,产品变体数据存储在多选 data-product_variations
元素的 <form class="variation_form">
属性中。变体数据以 JSON 格式存储,然后您可以使用 JSON.parse()
方法对其进行解码。无需通过 PHP 自己输出这些数据,因为 WooCommerce 已经为您完成了。
存储在 data-product_variations
属性中的 JSON 包括以下与价格相关的属性:
display_price
regular_price
sale_price
借助一点点 jQuery/JS,您可以使用上述属性轻松输出或更改默认或选定的变体定价。
祝你好运!