如何在Contact Form 7表单提交后显示指定div
解决Contact Form 7提交后在重定向页面显示指定div的问题
方法一:通过URL哈希检测实现(适配现有重定向链接)
- 默认隐藏目标div:在目标页面的CSS中添加样式,确保div默认不显示:
/* 替换为你实际使用的div类名/ID */ .success-content { display: none; }
- 添加哈希检测脚本:在目标页面的JS文件或
<script>标签中加入以下代码,识别CF7提交后的哈希并显示div:
document.addEventListener('DOMContentLoaded', function() { // 匹配CF7提交完成后的哈希标识 if (window.location.hash === '#wpcf7-f651-o1') { const targetDiv = document.querySelector('.success-content'); if (targetDiv) { targetDiv.style.display = 'block'; // 根据需求替换为flex等其他显示属性 // 可选:移除URL哈希,避免用户刷新页面时重复触发显示 window.history.replaceState(null, null, window.location.pathname); } } });
方法二:通过URL参数传递提交状态(更安全可靠)
若担心用户手动输入哈希触发显示,可改用URL参数的方式:
- 修改CF7重定向逻辑:在主题的
functions.php文件中添加以下PHP代码,让表单提交成功后携带状态参数跳转:
add_action('wpcf7_mail_sent', 'cf7_redirect_with_success_flag'); function cf7_redirect_with_success_flag($contact_form) { // 验证目标表单ID(此处为651,替换为你的实际表单ID) if ($contact_form->id() === 651) { $redirect_url = 'https://example.com/referr-mobile-app/?form_submitted=success'; wp_redirect($redirect_url); exit; } }
- 页面端检测参数并显示div:同样先给div添加隐藏样式,再加入JS检测代码:
document.addEventListener('DOMContentLoaded', function() { const urlParams = new URLSearchParams(window.location.search); if (urlParams.has('form_submitted') && urlParams.get('form_submitted') === 'success') { const targetDiv = document.querySelector('.success-content'); if (targetDiv) { targetDiv.style.display = 'block'; // 可选:移除URL参数优化页面体验 window.history.replaceState(null, null, window.location.pathname); } } });
注意事项
- 代码中的
.success-content需替换为你实际要显示的div的类名或ID(如用#success-div对应ID选择器)。 - 方法二中的
wpcf7_mail_sent钩子仅在邮件发送成功后触发,若需表单验证通过就跳转,可改用wpcf7_valid钩子。
内容的提问来源于stack exchange,提问作者Amrutha Lakshmi
相关产品推荐
相关产品推荐

