我已经创建了WooCommerce产品,并使用钩子woocommerce_before_add_to_cart_button
添加商品详细页上两个选项。现在,当顾客从产品详细信息页面添加产品到购物车时,他们有两种选择。他们可以从这两个选项中选择一个选项。更改WooCommerce车价格后应用优惠券代码
然后,我使用woocommerce hook woocommerce_add_cart_item_data将用户选定的值存储在购物车meta中。
我利用这个答案代码:Save product custom field radio button value in cart and display it on Cart page
这是我的代码:
// single Product Page options
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product");
function options_on_single_product(){
$dp_product_id = get_the_ID();
$product_url = get_permalink($dp_product_id);
?>
<input type="radio" name="custom_options" checked="checked" value="option1"> option1<br />
<input type="radio" name="custom_options" value="option2"> option2
<?php
}
//Store the custom field
add_filter('woocommerce_add_cart_item_data', 'save_custom_data_with_add_to_cart', 10, 2);
function save_custom_data_with_add_to_cart($cart_item_meta, $product_id) {
global $woocommerce;
$cart_item_meta['custom_options'] = $_POST['custom_options'];
return $cart_item_meta;
}
这是我曾尝试:
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price($cart_obj) {
if (is_admin() && ! defined('DOING_AJAX'))
return;
foreach ($cart_obj->get_cart() as $key => $value) {
$product_id = $value['product_id'];
$custom_options = $value['custom_options'];
$coupon_code = $value['coupon_code'];
if($custom_options == 'option2')
{
if($coupon_code !='')
{
global $woocommerce;
if (WC()->cart->has_discount($coupon_code)) return;
(WC()->cart->add_discount($coupon_code))
//code for second discount
}
else{
$percentage = get_post_meta($product_id , 'percentage', true);
//print_r($value);
$old_price = $value['data']->regular_price;
$new_price = ($percentage/100) * $old_price;
$value['data']->set_price($new_price);
}
}
}
}
现在我想做拿到最后的片段是:
- 如果客户选择了Option1,则运行woocommerce常规流程。
- 如果选择了选项2,则首先应用于购物车的优惠券代码(如果客户输入的代码)然后价格除以某个百分比(存储在产品元中)之后应用。
但它没有像预期的那样工作,因为更改的产品价格是女佣之前和优惠券折扣后应用此更改的价格。
我想要的是,优惠券折扣将首先应用于产品正常价格,然后通过我的自定义产品折扣更改此价格后。
这可能吗?我怎样才能做到这一点?
谢谢。