php - 自动应用或删除 Woocommerce 购物车中特定产品 ID 的优惠券

标签 php wordpress woocommerce cart coupon

当购物车中有产品 ID 1362 时,我会自动应用优惠券,但当有人添加其他产品并删除 1362 时,优惠券仍然适用,如果没有 1362 产品 ID,如何通过删除优惠券来防止这种情况发生在 Woocommerce 的购物车中?

我知道我们可以将优惠券限制在某个产品上,但我不希望这样,我希望仅当此购物车中存在 ID 为 1362 的产品时,我的优惠券才能应用于所有产品购物车。

add_action( 'woocommerce_before_cart', 'bbloomer_apply_matched_coupons' );

function bbloomer_apply_matched_coupons() {
    global $woocommerce;
    $coupon_code = 'boxpersonnalisable'; 
    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
    foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
    // this is your product ID
    $autocoupon = array( 1362 );
    if( in_array( $values['product_id'], $autocoupon ) ) {  
    add_filter('woocommerce_coupon_message','remove_msg_filter',10,3);
        $woocommerce->cart->add_discount( $coupon_code );
        wc_print_notices();
    }
    }
}

非常感谢

最佳答案

以下是使其在以下情况下工作的方法:

  • 将特定产品添加到购物车时添加特定优惠券代码
  • 从购物车中删除特定产品时删除特定的已应用优惠券代码
  • (在这两种情况下,您都可以显示自定义通知)...

代码:

add_action( 'woocommerce_before_calculate_totals', 'auto_add_remove_coupon' );
function auto_add_remove_coupon( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    $coupon_code = 'boxpersonnalisable';
    $targeted_product_ids = array( 1362 );
    $found = false;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( in_array( $cart_item['product_id'], $targeted_product_ids ) ){
            $found = true;
            break;
        }
    }

    if ( ! $cart->has_discount( $coupon_code ) && $found ) {
        $cart->add_discount( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __("Your custom notice - coupon added (optional)","woocommerce"), 'notice');
    } elseif  ( $cart->has_discount( $coupon_code ) && ! $found ) {
        $cart->remove_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __("Your custom notice - coupon removed (optional)","woocommerce"), 'notice');
    }
}

代码位于事件子主题(或事件主题)的 function.php 文件中。已测试并有效

关于php - 自动应用或删除 Woocommerce 购物车中特定产品 ID 的优惠券,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738432/

相关文章:

php - Laravel 邮件附件

php - 将多个日期添加到 Wordpress 中的自定义帖子类型

php - 从所有 WooCommerce 预订中获取所有人的总和

wordpress - MX 记录 mailgun 和 gsuite/gmail。在 mailgun 上使用子域 = 在我的 WP 主机(siteground)上添加子域?

php - 返回多个json结果

javascript - Google 图表导出为图像

php mysql插入不工作

php - 迁移到新主机后无法访问 WordPress 仪表板

wordpress - 如何使用 node-wordpress 的示例

php - 有没有办法在购物车中显示缺货消息,以具体指示哪些商品已售完?