应用优惠券代码

时间:2017-04-19 09:40:37

标签: php wordpress woocommerce cart product

我在WooCommerce上创建了一个产品,并使用钩子 woocommerce_before_add_to_cart_button 在产品详细信息页面上添加了两个选项。现在,当客户从产品详细信息页面将产品添加到购物车时,他们有两种选择。他们可以从这两个选项中选择一个选项。

然后我使用woocommerce hook woocommerce_add_cart_item_data将用户选择的值存储在购物车元数据中。

我正在使用此答案中的代码: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常规流程。
  • 如果选择Option2,则首先将优惠券代码应用于购物车(如果客户输入代码),然后将价格除以某个百分比(存储在产品元数据中)随后应用

但它没有按预期工作,因为之前的产品价格变化是女佣,而且在此变更价格后应用优惠券折扣。

我想要的是优惠券折扣将首先应用于产品正常价格,然后在我的定制产品折扣更改此价格后。

这可能吗?我怎样才能做到这一点?

感谢。

2 个答案:

答案 0 :(得分:4)

  

这不太可能 ......为什么? ... 因为(逻辑):

     
      
  1. 您有产品价格
  2.   
  3. 然后将优惠券折扣应用于该价格(之后)
      的 ==&GT;如果您更改产品价格,优惠券将适用于该更改的价格
  4.   

您可以做什么:

  1. 您不会改变产品价格
  2. 如果输入优惠券,则应用...
  3. 如果&#34; option2&#34;产品已添加到购物车:
  4. 根据使用WC_cart add_fee()方法后添加的产品价格,应用自定义折扣(负面费用)...
  5. 对于最后一种情况,您必须微调您的额外折扣 如果优惠券尚未使用或已被删除,则无额外折扣。

    您的自定义功能将隐藏在 woocommerce_cart_calculate_fees 操作挂钩中:

    add_action( 'woocommerce_cart_calculate_fees', 'option2_additional_discount', 10, 1 );
    function option2_additional_discount( $cart_obj ) {
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $discount = 0;
        $applied_coupons = $cart_obj->get_applied_coupons();
    
        foreach ( $cart_obj->get_cart() as $item_values ) {
            if( 'option2' == $item_values['custom_options'] && !empty($applied_coupons) ){
                $product_id = $item_values['product_id'];
                $percentage = get_post_meta( $product_id , 'percentage', true );
                $quantity = $item_values['quantity'];
                $product_reg_price = $item_values['data']->regular_price;
                $line_total = $item_values['line_total'];
                $line_subtotal = $item_values['line_subtotal'];
                $percentage = 90;
    
                ## ----- CALCULATIONS (To Fine tune) ----- ##
    
                $item_discounted_price = ($percentage / 100) *  $product_reg_price * $item_values['quantity'];
                // Or Besed on line item subtotal
                $discounted_price = ($percentage / 100) * $line_subtotal;
    
                $discount += $product_reg_price - $item_discounted_price;
            }
        }
        if($discount != 0)
            $cart_obj->add_fee( __( 'Option2 discount', 'woocommerce' ) , - $discount );
    }
    

    代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

    此代码经过测试并有效。

答案 1 :(得分:0)

使用WC_Cart->add_fee()方法添加负费用并不适合我。当我检查WC Cart类时,它甚至声明不允许使用负数。

See the docs.

我做了以下事情:

  • 使用“安全”创建占位符优惠券。代码,例如。 custom_discount_fjgndfl28 。设置折扣数量为0,所以当某人(某种程度上)在您的计划之外使用此优惠券时,折扣仍为0。
  • 使用过滤器woocommerce_get_shop_coupon_data,并为该优惠券/会话设置所需的所有优惠券数据。
  • 挂钩woocommerce_before_calculate_totals并将自定义优惠券设置为购物车。
  • 此时购物车应该正确计算所有内容。当它成为一个订单时,它也有正确的折扣安装。
  • 注意:优惠券代码也可用作某些模板中的标签。使用过滤器woocommerce_cart_totals_coupon_label进行更改。

示例功能:

/**
 * NOTE: All the hooks and filters below have to be called from your own
 * does_it_need_custom_discount() function. I used the 'wp' hook for mine.
 * Do not copy/paste this to your functions.php.
**/

add_filter('woocommerce_get_shop_coupon_data', 'addVirtualCoupon', 10, 2);
function addVirtualCoupon($unknown_param, $curr_coupon_code) {

    if($curr_coupon_code == 'custom_discount_fjgndfl28') {

      // possible types are: 'fixed_cart', 'percent', 'fixed_product' or 'percent_product.
      $discount_type = 'fixed_cart'; 

      // how you calculate the ammount and where you get the data from is totally up to you.
      $amount = $get_or_calculate_the_coupon_ammount;

      if(!$discount_type || !$amount) return false;

        $coupon = array(
            'id' => 9999999999 . rand(2,9),
            'amount' => $amount,
            'individual_use' => false,
            'product_ids' => array(),
            'exclude_product_ids' => array(),
            'usage_limit' => '',
            'usage_limit_per_user' => '',
            'limit_usage_to_x_items' => '',
            'usage_count' => '',
            'expiry_date' => '',
            'apply_before_tax' => 'yes',
            'free_shipping' => false,
            'product_categories' => array(),
            'exclude_product_categories' => array(),
            'exclude_sale_items' => false,
            'minimum_amount' => '',
            'maximum_amount' => '',
            'customer_email' => '',
            'discount_type' => $discount_type,
        );

        return $coupon;
    }
}

add_action('woocommerce_before_calculate_totals', 'applyFakeCoupons');
function applyFakeCoupons() {
  global $woocommerce;
  // $woocommerce->cart->remove_coupons(); remove existing coupons if needed.
  $woocommerce->cart->applied_coupons[] = $this->coupon_code; 
}

add_filter( 'woocommerce_cart_totals_coupon_label', 'cart_totals_coupon_label', 100, 2 );
function cart_totals_coupon_label($label, $coupon) {

    if($coupon) {
      $code = $coupon->get_code();
      if($code == 'custom_discount_fjgndfl28') {
        return 'Your custom coupon label';
      }
    }

    return $label;
}

请注意:我将这些功能复制到一个可以处理更多内容的课程中,它只是为了帮助您开始。

相关问题