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

WordPress 4.9.5自定义文章类型URL重写问题求助

解决WordPress 4.9.5自定义文章类型URL重写问题

嘿,我来帮你搞定这个URL重写需求!针对你提到的posts和store两个自定义文章类型,咱们一步步来实现把DOMAIN/single-post-name.html?hi=123&name=name-child-2改成DOMAIN/single-post-name/123/name-child-2.html的效果:

1. 添加自定义重写规则

首先,把下面的代码添加到你当前主题的functions.php文件里,它会告诉WordPress如何识别新的URL格式:

function custom_post_type_rewrite_rules() {
    // 匹配新的URL结构:单文章slug/数字参数/字符串参数.html
    add_rewrite_rule(
        '^([^/]+)/(\d+)/([^/]+)\.html$',
        'index.php?name=$matches[1]&hi=$matches[2]&child_name=$matches[3]',
        'top'
    );
}
add_action('init', 'custom_post_type_rewrite_rules');

注意:这里我把原参数name改成了child_name,因为WordPress本身的查询变量里有name(用来匹配文章slug),直接用会导致参数冲突,后续获取参数时要对应使用child_name。

2. 注册自定义查询变量

让WordPress允许识别我们新增的hi和child_name参数,同样添加到functions.php:

function custom_query_vars($vars) {
    $vars[] = 'hi';
    $vars[] = 'child_name';
    return $vars;
}
add_filter('query_vars', 'custom_query_vars');

3. 修改文章链接生成逻辑

接下来,我们需要让WordPress生成新格式的URL,替换原来带参数的链接:

function custom_post_type_permalink($permalink, $post) {
    // 只对posts和store自定义文章类型生效
    if (!in_array($post->post_type, array('posts', 'store'))) {
        return $permalink;
    }

    // 如果当前URL带有hi和name参数,就替换成新的格式
    if (isset($_GET['hi']) && isset($_GET['name'])) {
        $hi_value = sanitize_text_field($_GET['hi']);
        $child_name_value = sanitize_text_field($_GET['name']);
        // 替换原链接的.html后缀,拼接新的参数部分
        $permalink = str_replace('.html', "/{$hi_value}/{$child_name_value}.html", $permalink);
    }

    return $permalink;
}
add_filter('post_type_link', 'custom_post_type_permalink', 10, 2);

4. 刷新重写规则(关键步骤!)

添加完代码后,必须刷新WordPress的重写规则才能让新规则生效:

  • 登录WordPress后台,进入「设置」→「固定链接」页面
  • 不需要修改任何设置,直接点击「保存更改」按钮即可

5. 在模板中获取参数值

如果你需要在文章模板里使用这两个参数的值,可以用下面的代码:

// 获取hi参数的值
$hi = get_query_var('hi');
// 获取原name参数的值(现在对应child_name)
$child_name = get_query_var('child_name');

注意事项

  • 确保posts和store两个自定义文章类型的文章slug是唯一的,避免出现不同类型文章slug相同导致的URL冲突
  • 因为你使用的是WordPress 4.9.5,以上所有函数在这个版本中都是支持的,不用担心兼容性问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:06:13