我正在尝试根据产品ID和数量条件自动在我的WooCommerce商店中应用优惠券。我的最终目标是,当将所需产品的两(2)个添加到购物车时自动应用特定优惠券,并且每当将三(3)个所需产品添加到购物车时自动应用另一个优惠券到应用。单个数量的产品应该没有折扣。 以下是代码的正确版本,现在可以使用:
add_action( 'woocommerce_before_cart', 'conditional_auto_add_coupons' );
function conditional_auto_add_coupons() {
if ( !WC()->cart->is_empty() ){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 103;
$coupon1 = 'soccer-sibling-2';
$coupon2 = 'soccer-sibling-3';
// First cart loop: Counting number of subactegory items in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $target_pid == $cart_item['data']->id ){
// Removes any coupons in the cart already
WC()->cart->remove_coupons();
if( 2 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon1 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon1 );
wc_add_notice( __( 'The multiple sibling discount has been applied.', 'theme_domain' ), 'success' );
} elseif( 3 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon2 ) ){
WC()->cart->remove_coupons();
WC()->cart->add_discount( $coupon2 );
wc_add_notice( __( 'The multiple sibling discount has been applied.', 'theme_domain' ), 'success' );
}
// Recalculates Cart Totals to show correct price
WC()->cart->calculate_totals();
}
}
}
}
答案 0 :(得分:2)
Theres是你代码中的很多错误,它有点过时了...... 我已经在你的函数中重写了函数并将它挂在另一个钩子里。
以下是您重新访问的代码:
add_action( 'woocommerce_before_cart', 'conditional_auto_add_coupons' );
function conditional_auto_add_coupons() {
if ( !WC()->cart->is_empty() ){
// Define HERE your Targeted Product ID and coupons codes
$target_pid = 103;
$coupon1 = 'soccer-sibling-2';
$coupon2 = 'soccer-sibling-3';
// First cart loop: Counting number of subactegory items in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $target_pid == $cart_item['data']->id ){
if( 2 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon1 ) ){
WC()->cart->add_discount( $coupon1 );
wc_add_notice( __( 'A quantity discount of <strong>5%</strong> has been added.', 'theme_domain' ), 'success' );
} elseif( 3 == WC()->cart->get_cart_contents_count() && !WC()->cart->has_discount( $coupon2 ) ){
WC()->cart->add_discount( $coupon2 );
wc_add_notice( __( 'A quantity discount of <strong>10%</strong> has been added.', 'theme_domain' ), 'success' );
}
}
}
}
}
此代码包含活动子主题(或主题)的function.php文件或任何插件文件。
这应该有效,不会让你的网站崩溃,但我还没有真正测试过,因为这是非常特别的。