WordPress:为登录与未登录用户设置不同首页问题排查
解决登录/未登录用户不同首页时灵时不灵的问题
你当前代码的核心问题是直接修改了WordPress全局的page_on_front配置项——这个选项存在数据库里,是全站共用的设置。当多个用户同时访问时,登录用户访问会把首页改成front-page,紧接着未登录用户访问又会把设置改回默认页,两者互相覆盖,自然会出现时灵时不灵的情况。
正确的做法是在请求层面做用户身份判断,不要修改全局配置,推荐用template_redirect钩子实现:
方案1:直接加载对应页面模板(URL保持首页地址)
add_action('template_redirect', function() { // 仅在首页请求时处理 if (is_front_page()) { if (is_user_logged_in()) { // 获取登录用户对应的首页(注意去掉path前的斜杠) $target_page = get_page_by_path('front-page'); if ($target_page) { include(get_page_template_path($target_page)); exit; } } else { // 获取未登录用户的默认首页 $target_page = get_page_by_path(''); // 填入你的默认页slug if ($target_page) { include(get_page_template_path($target_page)); exit; } } } });
方案2:跳转到对应页面(URL会切换到目标页地址)
适合需要明确展示目标页URL的场景:
add_action('template_redirect', function() { if (is_front_page()) { if (is_user_logged_in()) { $target_url = get_permalink(get_page_by_path('front-page')); if ($target_url) { wp_redirect($target_url); exit; } } else { $target_url = get_permalink(get_page_by_path('')); // 填入你的默认页slug if ($target_url) { wp_redirect($target_url); exit; } } } });
额外注意点
- 移除
get_page_by_path参数里的开头斜杠,该函数接收的是页面slug,不需要斜杠前缀,否则可能找不到目标页面。 - 将代码放到当前主题的
functions.php文件,或者自定义插件中即可生效。
内容的提问来源于stack exchange,提问作者Irakli Mosidze
相关产品推荐
相关产品推荐

