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

WordPress:解决含country分类术语的自定义URL下single-interest模板404问题

问题修复方案

1. 修正重写规则函数

原代码的查询字符串存在参数重复与无效项,导致WordPress无法正确识别查询对象,修改后的函数如下:

add_filter('generate_rewrite_rules', 'country_cpt_generating_rule');
function country_cpt_generating_rule($wp_rewrite) {
    $rules = array();
    $terms = get_terms(array(
        'taxonomy' => 'country',
        'hide_empty' => false,
    ));

    $post_type = 'interest';
    foreach ($terms as $term) {
        // 修正查询参数:移除无效的interest参数,确保格式正确
        $rules[$term->slug . '/interest/([^/]+)/?$'] = 'index.php?post_type=' . $post_type . '&name=$matches[1]';
    }

    // 将自定义规则优先级设为默认规则之上
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
}

2. 添加post_type_link过滤器生成正确前端URL

为让自定义文章类型的链接自动生成为country_name/interest_term格式,需添加该过滤器(前提是每篇interest文章已关联对应country分类项):

add_filter('post_type_link', 'country_cpt_custom_permalink', 10, 3);
function country_cpt_custom_permalink($permalink, $post, $leavename) {
    if ($post->post_type === 'interest') {
        // 获取文章关联的首个country分类别名(可根据实际关联逻辑调整)
        $countries = wp_get_post_terms($post->ID, 'country', array('fields' => 'slugs'));
        if (!empty($countries)) {
            $country_slug = reset($countries);
            $permalink = home_url('/' . $country_slug . '/interest/' . $post->post_name . '/');
        }
    }
    return $permalink;
}

3. 刷新固定链接设置

完成代码修改后,进入WordPress后台设置→固定链接页面,直接点击「保存更改」按钮,强制WordPress更新重写规则(无需修改现有设置)。

4. 验证效果

此时访问https://www.example.com/country_name/interest_term,WordPress将正确识别为interest类型的单篇文章,自动加载single-interest.php模板,get_queried_object()也会返回对应的文章对象,不再出现404错误。

关键注意点

  • 原代码中interest=$matches[1]为无效参数,WordPress无法通过该参数定位文章,需使用name=$matches[1]配合post_type=interest完成查询。
  • 需确保每篇interest文章都关联了对应的country分类项,否则无法生成正确的自定义URL。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:35:19