我正在为我的 WooCommerce 网上商店中的产品制作自定义插件。一切正常,但我只需要一件事。当客户选中产品页面上的复选框时,必须在所选变体的原始价格上增加 30 美元。
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 );
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
$product = wc_get_product($product_id);
$price = $product->get_price();
if ($product->is_type( 'variable' )) {
$var_price = $product->get_price_html();
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $var_price + 30;
}
} else {
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $price + 30;
}
}
return $cart_item_data;
}
这部分:if( ! empty( $_POST['addon-card'] ) )
检查复选框是否被选中。
我的问题在这里:
$var_price = $product->get_price_html();
// extra pack checkbox
if( ! empty( $_POST['addon-card'] ) ) {
$cart_item_data['new_price'] = $var_price + 30;
}
$var_price
的值仅为 0。
所以我试图弄清楚如何获得所选变体的价格。
我尝试过 get_variation_prices()
和 get_variation_price()
但没有任何运气...
更新 我试图实现 this thread 中的代码。使用该代码,我可以获得所选变体的价格,但无法再添加 30 美元。
答案 0 :(得分:0)
您能否尝试在 WooCommerce 挂钩下动态更改价格?
add_filter('woocommerce_variation_prices_price', 'custom_variation_price_change', 9999, 2 );
add_filter('woocommerce_variation_prices_regular_price', 'custom_variation_price_change', 9999, 2 );
function custom_variation_price_change( $price, $variation, $product ) {
// add some conditional code as per your requirement
$price = $price+30;
}