某些产品变体的价格数据是按吨发送的。我需要将该数据转换为千克,然后乘以产品变化重量(千克)。我创建了一个名为 num_sal 的自定义元字段。当 num_sal = 1000 时,我必须应用此计算,否则我将保持价格不变。我需要在单个产品页面上显示此价格,并将产品价格发送到购物车并结帐。 我的第一个想法是更改数据库中的meta_value(除以1000),但我如何知道它何时已更改为正确的公斤值。如果价格发生变化,他们会再次大量发送。 所以我一直在使用javascript来显示选择时的变化价格
$(document).on('found_variation', ...
效果很好。现在,当且仅当我的自定义元数据“num_sal”= 1000 时,我需要更改这些变体的价格。 这是我的 JavaScript 代码,它正确显示所选价格,但没有考虑此元字段的 if 子句。 当此方法有效时,所选的变体价格应为variation.display_price / 1000 *variation.weight
wc_enqueue_js( "
$(document).on('found_variation', 'form.cart', function( event, variation ) {
if(variation.price_html)
var variationprice = variation.display_price * 1.2;
console.log(variation.display_price * 1.2);
const formatter = new Intl.NumberFormat('fr-FR', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
var variationpriceTTC = formatter.format(variation.display_price * 1.2);
console.log(variationpriceTTC);
var variationpriceHT = formatter.format(variation.display_price);
$('p.price').html(variationpriceHT + ' € HT - <span class=\"prixTTC\">' + variationpriceTTC + ' € TTC</span>');
$('.woocommerce-variation-price').hide();
});
$(document).on('hide_variation', 'form.cart', function( event, variation ) {
$('p.price').html('" . $price . "');
});
" );
预先感谢您的任何建议。
谢谢你的建议。这是我用来让它工作的代码。我正在使用 woocommerce 挂钩“woocommerce_product_variation_get_regular_price”和“woocommerce_product_variation_get_price”,因此我不会修改数据库中的元数据,而只是修改单个产品级别的产品价格以及后续的购物车和结帐价格(我不会在产品列表页)。
add_filter('woocommerce_product_variation_get_regular_price','custom_price_2', 99, 2 ); add_filter('woocommerce_product_variation_get_price', 'custom_price_2' , 99, 2 );
// Variations (of a variable product)
add_filter('woocommerce_variation_prices_price', 'custom_variation_price', 99, 3 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price', 99, 3 );
function custom_price_2( $price, $product ) {
// Delete product cached price (if needed)
wc_delete_product_transients($product->get_id());
$product_id = $product->get_id();
$weight_1000 = get_post_meta($product_id, 'num_sal', true) ;
$variation_weight = $product->get_weight();
if ($weight_1000 = "1000"){
return $price / 1000 * $variation_weight;
}
else {
return $price;
}
}
function custom_variation_price( $price, $variation, $product ) {
// Delete product cached price (if needed)
wc_delete_product_transients($variation->get_id());
$weight_1000 = $variation->get_meta( 'num_sal' ) ;
$variation_weight = $variation->get_weight();
if ($weight_1000 = "1000"){
return (float)$price / 1000 * (float)$variation_weight;
}
else {
return $price;
}
}