You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于作者ID自定义WordPress文章的永久链接URL结构?

WordPress针对特定作者文章添加URL前缀实现方案

你当前的代码存在两处核心逻辑错误,无法实现需求:

  1. 直接全局修改WordPress固定链接结构,会统一修改所有文章的URL,无法实现针对特定作者的差异化规则
  2. 参数逻辑错误:get_user_by()返回的是用户对象,不能直接作为get_posts()的查询参数,同时就算查询到作者7的文章就全局改结构,也会覆盖所有其他作者的URL规则

正确实现需要借助WordPress原生钩子完成,直接将以下代码替换你原来写在functions.php中的代码即可:

// 1. 生成文章链接时,给作者ID为7的文章添加自定义前缀
add_filter('post_link', 'custom_author_post_permalink', 10, 3);
function custom_author_post_permalink($permalink, $post, $leavename) {
    // 仅对已发布的公开文章生效
    if ($post->post_type !== 'post' || $post->post_status !== 'publish') {
        return $permalink;
    }
    // 判断文章作者是否为ID 7
    if ($post->post_author == 7) {
        $permalink = home_url('/_blog/_blog_post/' . $post->post_name . '/');
    }
    return $permalink;
}

// 2. 添加重写规则,保证带前缀的URL可以正常访问不会404
add_filter('rewrite_rules_array', 'custom_author_rewrite_rules');
function custom_author_rewrite_rules($rules) {
    $new_rules = [
        // 匹配自定义前缀后的文章slug,映射到WordPress标准查询逻辑
        '_blog/_blog_post/([^/]+)/?$' => 'index.php?name=$matches[1]'
    ];
    // 把新规则放到原有规则前面,优先匹配
    return $new_rules + $rules;
}

生效操作

代码添加完成后,进入WordPress后台「设置」-「固定链接」页面,不需要修改任何现有设置,直接点击底部的「保存更改」按钮,刷新重写规则即可生效。

内容的提问来源于stack exchange,提问作者Yucaree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:48:04