You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Popups for WooCommerce Pro弹窗显示WooCommerce优惠券消息

实现WooCommerce优惠券消息在Popups for WooCommerce Pro弹窗中展示

需求说明:

  • 使用付费插件《Popups for WooCommerce: Add to Cart, Checkout & More》Pro版,将WooCommerce的两类优惠券消息("优惠券代码应用成功"和"优惠券代码不存在")展示在弹窗内
  • 插件无官方技术支持,仅文档说明可通过[ttt_pnwc_get_message]短代码调用任意过滤器的动态消息,示例:[ttt_pnwc_get_message filter="wc_add_to_cart_message_html"]

自行编写的代码如下,需技术协助优化:

add_filter('woocommerce_coupon_error', 'coupon_error_message_change', 10, 3);

function coupon_error_message_change($err, $err_code, $parm) {
    switch ($err_code) {
        case 105:
            /* translators: %s: coupon code */
            $err = sprintf(__('Coupon "%s" does not exist!', 'woocommerce'), $parm->get_code());

            // Using the message in a popup
            $dynamic_message = esc_html($err);
            
            // Display the dynamic message in the popup using the shortcode
            echo do_shortcode("[ttt_pnwc_get_message message='$dynamic_message']");
            break;
    }
    return $err;
}

代码问题分析及修正方案

原代码的核心问题:在woocommerce_coupon_error过滤器钩子中直接echo短代码,会打乱WordPress的输出流程,导致页面渲染异常。插件的短代码设计更适合通过绑定过滤器来获取消息,而非直接传入文本参数。

修正后的完整代码

// 处理优惠券错误消息(如不存在、过期等)
add_filter('woocommerce_coupon_error', 'custom_coupon_error_for_popup', 10, 3);
function custom_coupon_error_for_popup($err, $err_code, $parm) {
    // 针对优惠券不存在的错误码105
    if ($err_code === 105) {
        $err = sprintf(__('Coupon "%s" does not exist!', 'woocommerce'), $parm->get_code());
    }
    // 添加自定义过滤器,供弹窗插件获取消息
    add_filter('custom_coupon_message', function() use ($err) {
        return $err;
    });
    return $err;
}

// 处理优惠券成功应用消息
add_filter('woocommerce_coupon_message', 'custom_coupon_success_for_popup', 10, 3);
function custom_coupon_success_for_popup($msg, $coupon, $discount_amount) {
    $msg = __('Coupon code applied successfully!', 'woocommerce');
    // 添加自定义过滤器,供弹窗插件获取消息
    add_filter('custom_coupon_message', function() use ($msg) {
        return $msg;
    });
    return $msg;
}

弹窗配置步骤

  1. 打开Popups for WooCommerce Pro的弹窗编辑界面
  2. 在弹窗内容区域添加短代码:[ttt_pnwc_get_message filter="custom_coupon_message"]
  3. 保存弹窗设置,测试优惠券应用/错误场景

注意事项

  • 若需处理其他优惠券错误类型(如过期、已使用),可在woocommerce_coupon_error函数中添加更多$err_code判断
  • 始终保持过滤器钩子的职责为返回值,避免直接输出内容,防止破坏页面渲染流程
  • 测试时需覆盖所有优惠券交互场景,确保消息能正确触发弹窗

内容的提问来源于stack exchange,提问作者Shane Price

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:52:29