WordPress如何不使用插件通过代码实现Contact Form 7表单点击弹窗显示
Contact Form 7 点击按钮弹窗展示表单实现方案
无需额外插件,仅需添加三段代码即可完成实现,步骤如下:
步骤1:获取你的CF7表单短码
进入WordPress后台「Contact」-「Contact Forms」,复制对应表单的短码,格式类似[contact-form-7 id="123" title="联系表单"],后续要替换到代码中。
步骤2:插入HTML结构
在需要展示触发按钮的页面/主题模板位置插入以下代码:
<!-- 弹窗触发按钮,文字可自行修改 --> <button id="openContactFormBtn" class="cf7-popup-trigger">联系我们</button> <!-- 弹窗容器 --> <div id="cf7Popup" class="cf7-popup-overlay"> <div class="cf7-popup-content"> <!-- 弹窗关闭按钮 --> <span class="cf7-popup-close">×</span> <!-- 这里替换成你自己的CF7表单短码 --> <!-- 如果是在主题模板中插入,可使用<?php echo do_shortcode('你的短码'); ?> --> [contact-form-7 id="123" title="联系表单"] </div> </div>
步骤3:添加CSS样式
将以下样式添加到WordPress后台「外观」-「自定义」-「额外CSS」中,或主题的style.css文件内:
/* 弹窗遮罩层默认隐藏 */ .cf7-popup-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); z-index: 99999; justify-content: center; align-items: center; } /* 弹窗内容区域 */ .cf7-popup-content { background: #ffffff; padding: 2rem; border-radius: 8px; width: 90%; max-width: 500px; position: relative; box-sizing: border-box; } /* 关闭按钮样式 */ .cf7-popup-close { position: absolute; top: 1rem; right: 1rem; font-size: 1.5rem; cursor: pointer; color: #666666; line-height: 1; } /* 触发按钮样式,可根据需求自行调整 */ .cf7-popup-trigger { padding: 0.8rem 1.5rem; background: #2385bb; color: #ffffff; border: none; border-radius: 4px; cursor: pointer; font-size: 1rem; }
步骤4:添加JS交互逻辑
将以下JS代码添加到主题的自定义JS文件中,或直接在页面底部的自定义HTML块中插入:
document.addEventListener('DOMContentLoaded', function() { const openBtn = document.getElementById('openContactFormBtn'); const popup = document.getElementById('cf7Popup'); const closeBtn = document.querySelector('.cf7-popup-close'); // 点击按钮打开弹窗 openBtn.addEventListener('click', function() { popup.style.display = 'flex'; }); // 点击关闭按钮关闭弹窗 closeBtn.addEventListener('click', function() { popup.style.display = 'none'; }); // 点击遮罩层空白区域关闭弹窗 popup.addEventListener('click', function(e) { if (e.target === popup) { popup.style.display = 'none'; } }); // 可选功能:表单提交成功后自动关闭弹窗 document.addEventListener('wpcf7mailsent', function() { popup.style.display = 'none'; // 可在此处添加提交成功后的自定义提示,比如 alert('提交成功,我们会尽快联系你'); }, false); });
注意事项
- 所有代码添加完成后如果使用了缓存插件,需要清空缓存再测试功能
- 如果弹窗被其他内容遮挡,可调整
.cf7-popup-overlay的z-index值,调大到大于页面其他元素的层级即可 - 按钮、弹窗的样式都可以根据自己的网站风格修改CSS参数
内容的提问来源于stack exchange,提问作者Yusuf ElNu'man
相关产品推荐
相关产品推荐

