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

如何在Contact Form 7成功消息(wpcf7-messages[mail_sent_ok])中允许使用HTML标签

问题原因

你使用的wpcf7_mail_sent_ok钩子返回的内容,后续Contact Form 7会再执行全局HTML转义,同时前端默认用textContent插入响应消息,所以即使后端做了解码也无法正常渲染HTML结构。

完整实现方案

第一步:后端逻辑配置

将以下代码加入主题functions.php或自定义代码片段插件中,替换原有过滤逻辑:

// 适配AJAX提交场景,保留HTML结构
add_filter('wpcf7_ajax_json_echo', 'custom_cf7_html_response', 10, 2);
function custom_cf7_html_response($response, $result) {
    // 仅处理提交成功的请求
    if ($result['status'] !== 'mail_sent') return $response;

    // 获取表单提交的主题字段,注意替换为你表单内主题字段的name属性
    $submit_subject = isset($_POST['your-subject']) ? sanitize_text_field($_POST['your-subject']) : '';
    
    // 根据主题匹配对应Elementor模板,替换为你实际的模板ID
    if ($submit_subject === 'aa') {
        $response['message'] = do_shortcode('[elementor-template id="123"]');
    } elseif ($submit_subject === 'bb') {
        $response['message'] = do_shortcode('[elementor-template id="456"]');
    }

    return $response;
}

// 兼容非AJAX提交的场景
add_filter('wpcf7_display_message', 'custom_cf7_html_display', 10, 2);
function custom_cf7_html_display($message, $status) {
    if ($status !== 'mail_sent') return $message;

    $submit_subject = isset($_POST['your-subject']) ? sanitize_text_field($_POST['your-subject']) : '';
    if ($submit_subject === 'aa') {
        $message = do_shortcode('[elementor-template id="123"]');
    } elseif ($submit_subject === 'bb') {
        $message = do_shortcode('[elementor-template id="456"]');
    }

    return $message;
}

第二步:前端渲染配置

添加以下JS代码到主题自定义JS区域,或通过wp_footer钩子输出,让前端支持解析HTML消息:

document.addEventListener('wpcf7submit', function(event) {
    setTimeout(() => {
        const form = event.target;
        const responseBox = form.querySelector('.wpcf7-response-output');
        if (responseBox && event.detail.status === 'mail_sent') {
            const rawContent = responseBox.textContent;
            responseBox.innerHTML = rawContent;
        }
    }, 100);
}, false);

注意事项

  • 代码中的your-subject需替换为你Contact Form 7表单内主题字段对应的name属性
  • 短代码中的数字需替换为你自己后台Elementor模板对应的ID
  • 若Elementor模板内有交互功能,需确认模板资源已在表单所在页面正常加载

内容的提问来源于stack exchange,提问作者Gökhan Lüleci

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:48:03