WordPress functions.php:未登录时排除特定页面注销样式问题
解决未登录用户样式注销时特定页面例外不生效的问题
需求是未登录用户访问站点时注销指定样式,但ID为51519、别名为forums的页面要排除在外。目前已在BuddyBoss子主题的functions.php中添加代码,但目标页面仍被执行了样式注销操作;尝试补充关键CSS后布局仍异常,需修正代码实现页面例外逻辑。
当前使用的代码:
add_action('wp_enqueue_scripts','my_deregister_custom',100); function my_deregister_custom() { if ( !is_user_logged_in() ) { wp_deregister_style('dashicons'); if ( !is_page( array(51519,'forums'))) { wp_deregister_style('buddyboss-theme-forums'); wp_deregister_style('bp-mentions-css'); wp_deregister_style('learndash-front'); wp_deregister_style('buddyboss-theme'); wp_deregister_style('ldx-design-upgrade-learndash'); wp_deregister_style('buddyboss-theme-learndash'); wp_deregister_style('elementor-frontend'); } } }
问题分析
你用is_page()判断页面,但如果目标页面是BuddyBoss集成的bbPress论坛页面,它可能不属于默认的page类型,导致is_page()无法正确识别,所以例外规则失效。
修正方案
方案1:用bbPress专属判断函数
BuddyBoss的论坛基于bbPress,直接用is_bbpress()判断论坛页面,同时保留原有的ID和别名判断,兼容性更强:
add_action('wp_enqueue_scripts','my_deregister_custom',100); function my_deregister_custom() { if ( !is_user_logged_in() ) { wp_deregister_style('dashicons'); // 同时排除bbPress论坛页面、指定ID和别名的页面 if ( !is_bbpress() && !is_page( array(51519,'forums'))) { wp_deregister_style('buddyboss-theme-forums'); wp_deregister_style('bp-mentions-css'); wp_deregister_style('learndash-front'); wp_deregister_style('buddyboss-theme'); wp_deregister_style('ldx-design-upgrade-learndash'); wp_deregister_style('buddyboss-theme-learndash'); wp_deregister_style('elementor-frontend'); } } }
方案2:通过Slug或URL精准判断
如果is_bbpress()不生效,直接判断页面slug或者URL路径,确保不会漏判:
add_action('wp_enqueue_scripts','my_deregister_custom',100); function my_deregister_custom() { if ( !is_user_logged_in() ) { wp_deregister_style('dashicons'); global $post; $current_slug = isset($post->post_name) ? $post->post_name : ''; // 排除指定ID、别名,以及URL包含/forums/的页面 if ( !(is_page(51519) || $current_slug === 'forums' || strpos($_SERVER['REQUEST_URI'], '/forums/') !== false) ) { wp_deregister_style('buddyboss-theme-forums'); wp_deregister_style('bp-mentions-css'); wp_deregister_style('learndash-front'); wp_deregister_style('buddyboss-theme'); wp_deregister_style('ldx-design-upgrade-learndash'); wp_deregister_style('buddyboss-theme-learndash'); wp_deregister_style('elementor-frontend'); } } }
额外提示
- 如果还是不生效,把钩子优先级从
100改成999,确保代码在样式注册之后执行。 - 可以在目标页面临时加
var_dump(is_page(51519))或var_dump(is_bbpress()),看看这些判断函数是否返回true,排查识别问题。
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

