WordPress中用户未填billing_phone时触发Elementor弹窗问题求助
问题分析与修复方案
你的代码有两个核心问题导致无法正常工作:
- 逻辑判断完全搞反:需求是未填写手机号时显示弹窗,但你写的是手机号不为空时才执行弹窗代码;
- Elementor弹窗触发方式错误:直接点击弹窗DOM元素不是官方触发方式,弹窗默认处于隐藏状态,这种操作大概率无效。
以下是修正后的完整代码:
function display_elementor_popup_based_on_billing_phone() { // 先判断用户是否登录,未登录用户无billing_phone字段 if (is_user_logged_in()) { $current_user = wp_get_current_user(); $billing_phone = get_user_meta($current_user->ID, 'billing_phone', true); // 当billing_phone为空时,输出弹窗触发代码 if (empty($billing_phone)) { ?> <script> document.addEventListener('DOMContentLoaded', function() { // 使用Elementor官方弹窗API触发指定ID的弹窗 if (typeof elementorProFrontend !== 'undefined' && elementorProFrontend.modules.popups) { elementorProFrontend.modules.popups.showPopup({ id: 36698 }); } }); </script> <?php } } } add_shortcode('billing_phone_elementor_popup', 'display_elementor_popup_based_on_billing_phone');
关键改动说明:
- 修正判断逻辑:将
!empty($billing_phone)改为empty($billing_phone),匹配「手机号为空时显示弹窗」的需求; - 增加登录判断:通过
is_user_logged_in()排除未登录用户,避免无billing_phone字段的游客误触发弹窗; - 使用官方API:调用Elementor Pro的
showPopup方法触发弹窗,这是官方推荐的正确方式,比直接操作DOM元素更可靠; - 增加API存在判断:通过
typeof elementorProFrontend !== 'undefined'避免因Elementor未加载完全导致的JS报错。
使用方法:将修正后的代码添加到主题的functions.php文件,或通过自定义代码插件添加,然后在需要的页面插入短代码[billing_phone_elementor_popup]即可。
内容的提问来源于stack exchange,提问作者Shane Price
相关产品推荐
相关产品推荐

