Woocommerce指定商品需优惠券才可购买代码失效求助
特定商品需指定优惠券才能购买的代码排查与修复
我找到一段实现“特定商品必须使用指定优惠券才能结算”的代码,但无法正常运行,希望帮忙排查解决。原代码如下:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' ); function mandatory_coupon_for_specific_items() { $targeted_ids = array(37); // 目标商品ID数组 $coupon_code = 'summer2'; // 要求使用的优惠券码 $coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() ); // 遍历购物车商品 foreach(WC()->cart->get_cart() as $cart_item ) { // 检查商品是否为目标商品且未应用优惠券 if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) { wc_clear_notices(); // 清除所有其他提示 // 提示用户需要优惠券才能结算 wc_add_notice( sprintf( '商品"%s"需要使用指定优惠券才能结算。', $cart_item['data']->get_name() ), 'error' ); break; // 终止循环 } } }
问题排查
原代码无法运行的核心原因是HTML转义字符未还原(比如->、&&这类HTML实体直接放到PHP中会触发语法错误),同时缺少购物车对象的存在性检查,极端场景下会导致报错。
修复后的代码
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' ); function mandatory_coupon_for_specific_items() { // 目标商品ID数组(可添加多个ID) $targeted_ids = array(37); // 要求使用的优惠券码 $coupon_code = 'summer2'; // 提前检查购物车对象是否存在,避免报错 if ( ! WC()->cart ) { return; } // 将已应用的优惠券统一转为小写,避免大小写匹配问题 $applied_coupons = array_map( 'strtolower', WC()->cart->get_applied_coupons() ); $coupon_applied = in_array( strtolower($coupon_code), $applied_coupons ); // 遍历购物车中的所有商品 foreach( WC()->cart->get_cart() as $cart_item ) { // 匹配目标商品且未使用指定优惠券时,触发错误提示 if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) { wc_clear_notices(); // 清除其他无关提示 // 输出清晰的错误提示,阻止用户结算 wc_add_notice( sprintf( '商品"%s"必须使用指定优惠券才能完成结算。', $cart_item['data']->get_name() ), 'error' ); break; // 找到目标商品后终止循环,提升效率 } } }
使用说明
- 确认
$targeted_ids中的商品ID与实际商品ID一致(可在WooCommerce商品编辑页面的URL中查看ID) - 确认
$coupon_code对应的优惠券已在后台创建,且状态为启用 - 将代码添加到当前主题的
functions.php文件中,或使用自定义代码插件(如Code Snippets)添加 - 测试验证:添加目标商品到购物车,未使用优惠券时点击结算,应弹出错误提示;应用指定优惠券后可正常进入结算流程
内容的提问来源于stack exchange,提问作者Uzair Ahmed
相关产品推荐
相关产品推荐

