如何将通用占位URL重定向到登录用户对应的Custom Post作者页面
实现思路
- 提前在WordPress后台新建固定链接为
my-profile的空白占位页,无需填写内容 - 挂载WordPress原生
template_redirect钩子,在页面模板加载前执行重定向逻辑 - 核心判断流程:
- 校验当前访问页面是否为
my-profile占位页 - 校验用户是否处于登录状态
- 登录用户则查询其作为作者的对应自定义文章类型内容,获取永久链接后执行重定向
- 校验当前访问页面是否为
- 异常兼容:未登录用户访问时可跳转至登录页;用户未生成对应个人页时可触发自动生成逻辑或跳转提示页
可直接使用的实现代码
将以下代码添加到当前主题的functions.php文件,或自定义功能插件中即可生效:
add_action('template_redirect', 'redirect_my_profile_to_user_cpt'); function redirect_my_profile_to_user_cpt() { // 配置参数:请替换为你自己的实际配置 $placeholder_page_slug = 'my-profile'; // 占位页的slug $profile_cpt_slug = 'users'; // 你注册的个人资料自定义文章类型的slug $login_url = wp_login_url(home_url('/' . $placeholder_page_slug)); // 未登录时跳转的登录页,登录后自动跳回my-profile // 不是访问占位页直接跳过 if (!is_page($placeholder_page_slug)) return; // 未登录用户跳登录 if (!is_user_logged_in()) { wp_redirect($login_url); exit; } $current_user = wp_get_current_user(); // 查询当前用户对应的自定义文章 $profile_query = new WP_Query([ 'post_type' => $profile_cpt_slug, 'author' => $current_user->ID, 'post_status' => 'publish', 'posts_per_page' => 1, 'no_found_rows' => true ]); if ($profile_query->have_posts()) { // 查到个人页则302重定向(如果需要永久跳转改为301即可) wp_redirect(get_permalink($profile_query->post->ID), 302); exit; } // 没有查到对应个人页的兜底逻辑,可按需修改,比如跳转到首页加提示 wp_redirect(home_url('/?notice=no_profile')); exit; }
测试注意事项
- 代码配置部分的两个slug要和你实际的占位页slug、自定义文章类型slug对应
- 如果使用301重定向,测试前要清空浏览器缓存,避免之前的重定向缓存影响测试结果
- 若需要修改未登录、无个人页的跳转规则,直接修改代码中对应
wp_redirect的参数即可
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

