WooCommerce自定义优惠券短代码:识别已应用优惠券并提示
核心问题定位
- 表单无法正常渲染的根因是代码括号层级错位:原本属于短代码主流程的表单HTML生成逻辑,被错误嵌套在「携带优惠券提交参数」的判断分支内部,未触发提交动作时代码根本走不到输出表单的环节,最终表现为短代码输出空内容。
- 重复优惠券判断逻辑完全失效:原代码将
WC()->cart->apply_coupon()返回的布尔值,和购物车已应用优惠券的数组做等值比较,永远无法匹配对应分支;同时判断顺序颠倒,没有先校验优惠券是否已经生效就直接执行应用动作,自然会抛出“优惠券不存在”的错误提示。 - 逻辑冲突点:未清理WooCommerce系统默认的优惠券提示,会和自定义反馈弹窗重复展示。
修正后可正常运行的完整代码
add_shortcode( 'coupon', 'redeem_coupon_form' ); function redeem_coupon_form() { // 订单支付完成页不渲染兑换表单 if ( is_wc_endpoint_url( 'order-received' ) ) return; $custom_message = ''; // 处理优惠券提交动作 if ( isset( $_GET['coupon'] ) && isset( $_GET['redeem-coupon'] ) ) { $coupon_code = sanitize_text_field( $_GET['coupon'] ); $already_applied_list = WC()->cart->get_applied_coupons(); // 优先判断优惠券是否已应用到购物车 if ( in_array( $coupon_code, $already_applied_list, true ) ) { $custom_message = sprintf( __('<br><p class="coupon-code-already-applied">You have already applied "%s" and can therefore not apply it again.</p>'), $coupon_code ); } else { // 未应用则尝试执行兑换动作 $apply_status = WC()->cart->apply_coupon( $coupon_code ); if ( $apply_status ) { $custom_message = sprintf( __('<br><p class="coupon-code-does-exist">Thanks for applying the "%s" coupon<br />Please make sure everything checks out before paying.</p>'), $coupon_code ); } else { $custom_message = sprintf( __('<br><p class="coupon-code-does-not-exist">Ops! What happened? The "%s" coupon does not exist.<br />Please check the coupon name, alternative - your spelling.</p>'), $coupon_code ); } } // 清除WooCommerce系统默认的优惠券提示,避免和自定义反馈冲突 wc_clear_notices(); } // 表单生成逻辑独立于提交判断分支,保证所有访问场景下都能正常渲染 $output = '<div class="redeem-coupon"><form id="coupon-redeem"> <input style="display:block; width: 65%; margin-right: 1%; height: 50px; border:1px solid #333; padding: 0px; float: left;" type="text" name="coupon" id="coupon" placeholder="  Coupon Code Here" /> <input style="display:block; margin: 0px; width: 34%; height: 51px; padding: 0px;" type="submit" class="redeem-coupon-button" name="redeem-coupon" value="'.__('Redeem Coupon').'" />'; $output .= !empty( $custom_message ) ? '<p class="result"> ' . $custom_message . ' </p>' : ''; return $output . '</form></div>'; }
场景适配验证
- 提交未使用的有效优惠券:正常触发兑换成功提示,购物车正确加载折扣
- 提交不存在的无效优惠券:正常触发“优惠券不存在”的错误提示
- 重复提交已经生效的优惠券:触发“优惠券已应用”的专属提示,不再弹出系统默认错误
- 正常访问包含短代码的页面:兑换表单完整渲染,无内容缺失
内容的提问来源于stack exchange,提问作者user14906105
相关产品推荐
相关产品推荐

