激活UsersWP插件后WordPress中Bootstrap模态框秒关如何解决
问题解决方法
问题根源
- 站点同时加载了两次Bootstrap JS:你自己主题/其他功能引入的Bootstrap,和UsersWP插件加载的
bootstrap.bundle.min.js冲突,两个JS都绑定了模态框事件,触发时会一次打开一次关闭,就出现了模态框打开1秒自动消失的问题 - 你之前的移除代码不生效的核心原因是:
wp_deregister_script()的参数是WordPress脚本注册时的句柄(handle),不是文件名
操作步骤
步骤1:查找冲突脚本的注册句柄
WordPress加载的脚本都会在script标签上带有id,格式为[句柄]-js,你可以直接查看个人资料页的页面源码,找到UsersWP引入的bootstrap.bundle.min.js对应的script标签,比如标签是:<script id='ayecode-ui-bootstrap-js' src='https://example.com/wp-content/plugins/userswp/vendor/ayecode/wp-ayecode-ui/assets/js/bootstrap.bundle.min.js'></script>
那么该脚本的句柄就是ayecode-ui-bootstrap(去掉末尾的-js即可)
如果找不到也可以用临时调试代码获取:
将以下代码临时加入子主题functions.php,访问个人资料页即可输出对应句柄,获取后立即删除该调试代码:
add_action( 'wp_enqueue_scripts', 'debug_get_bootstrap_handle', 9999 ); function debug_get_bootstrap_handle() { global $wp_scripts; // 个人资料页判断如果是作者归档页请替换为is_author() if ( is_page('my-account') ) { foreach( $wp_scripts->registered as $handle => $script ) { if ( strpos( $script->src, 'bootstrap.bundle.min.js' ) !== false ) { echo '冲突脚本句柄为:' . $handle; } } die; } }
步骤2:添加正确的移除代码
将以下代码加入子主题functions.php,替换其中的句柄为你上一步获取到的实际句柄:
add_action( 'wp_enqueue_scripts', 'remove_userswp_bootstrap_conflict', 200 ); function remove_userswp_bootstrap_conflict() { // 个人资料页判断如果是作者归档页请替换为is_author() if ( is_page('my-account') ) { // 替换为你获取到的实际句柄 $target_handle = 'ayecode-ui-bootstrap'; wp_dequeue_script( $target_handle ); wp_deregister_script( $target_handle ); } }
这里用优先级200是为了保证执行时机晚于UsersWP注册脚本的时机,确保可以成功移除。
可选:修正模态框初始化代码
你现有模态框的JS代码存在语法错误,第二行选择器漏了#,建议修正:
$( '#exampleModal<?php echo esc_html($list->id);?>' ).click( function(e) { e.preventDefault(); // 这里原代码漏了# $( '#exampleModal<?php echo esc_html($list->id);?>' ).modal(); });
内容的提问来源于stack exchange,提问作者qazidev
相关产品推荐
相关产品推荐

