在 WooCommerce 中应用特定优惠券时添加免费产品

2023-12-23

当通过以下方式使用特定优惠券时,我可以将产品添加到购物车woocommerce_applied_coupon钩子和add_to_cart()功能

add_action('woocommerce_applied_coupon', 'apply_product_on_coupon');
function apply_product_on_coupon( ) {
    global $woocommerce;
    $coupon_id = 'mybday';
    $free_product_id = 131468;

    if(in_array($coupon_id, $woocommerce->cart->get_applied_coupons())){
        $woocommerce->cart->add_to_cart($free_product_id, 1);
    }
}

我的问题:有没有办法在同一个回调函数中将其折扣为 0?


您当前的代码包含一些错误或可以优化:

  • global $woocommerce可以替换为WC()
  • $woocommerce->cart->get_applied_coupons()不是必需的,因为已应用的优惠券将传递给回调函数。

相反,使用最后一个可用参数WC_Cart::add_to_cart() https://woocommerce.wp-a2z.org/oik_api/wc_cartadd_to_cart/方法,该方法允许您添加任何自定义购物车项目数据。然后您将能够轻松地从购物车对象获取该数据。

所以你得到:

function action_woocommerce_applied_coupon( $coupon_code ) {
    // Settings
    $product_id = 131468;
    $quantity = 1;
    $free_price = 0;
    $coupon_codes = array( 'coupon1', 'mybday' );

    // Compare
    if ( in_array( $coupon_code, $coupon_codes ) ) {
        // Add product to cart
        WC()->cart->add_to_cart( $product_id, $quantity, 0, array(), array( 'free_price' => $free_price ) );
    }
}
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 1 );

// Set free price from custom cart item data
function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    // Loop through cart contents
    foreach ( $cart->get_cart_contents() as $cart_item ) {       
        if ( isset( $cart_item['free_price'] ) ) {
            $cart_item['data']->set_price( $cart_item['free_price'] );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );

Note:除了使用woocommerce_applied_coupon,您还必须使用woocommerce_removed_coupon因为当优惠券被删除时,产品也会被删除

function action_woocommerce_removed_coupon( $coupon_code ) {
    // Settings
    $product_id = 131468;
    $coupon_codes = array( 'coupon1', 'mybday' );

    // Compare
    if ( in_array( $coupon_code, $coupon_codes ) ) {
        // Loop through cart contents
        foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
            // When product in cart
            if ( $cart_item['product_id'] == $product_id ) {
                // Remove cart item
                WC()->cart->remove_cart_item( $cart_item_key );
                break;
            }
        }
    }
}
add_action( 'woocommerce_removed_coupon', 'action_woocommerce_removed_coupon', 10, 1 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 WooCommerce 中应用特定优惠券时添加免费产品 的相关文章

随机推荐