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

WordPress嵌套自定义文章类型URL重写404问题求助

WordPress嵌套自定义文章类型URL 404问题解决

问题背景

搭建WordPress站点时使用两个嵌套自定义文章类型,期望实现以下URL结构:

  • https://website.com/news/:显示常规WordPress文章(已正常运行)
  • https://website.com/events/:显示自定义events类型的文章列表(已正常运行)
  • https://website.com/events/an-event/:单个event详情页(已正常运行)
  • https://website.com/events/an-event/ride-01/:自定义rides类型的文章实例(访问出现404错误)

后台可正常创建rides内容,预览链接显示正确,但前端访问对应URL时返回404。直接访问https://website.com/index.php?rides=ride-01可正常显示rides内容。已尝试调整rewrite和hierarchy参数,且每次修改后保存固定链接页面清除缓存,问题仍未解决。

问题原因与修复方案

1. 重写规则格式错误

原重写规则开头多了斜杠/,WordPress的rewrite规则不需要开头的斜杠,导致规则无法匹配请求URL。

2. 优化修复步骤

(1)修正重写规则

将原规则开头的斜杠删除,确保规则能正确匹配URL结构:

add_action('init', function () {
    add_rewrite_rule('^events/([^/]+)/([^/]+)/?$', 'index.php?rides=$matches[2]', 'top');
});

(2)显式指定rides的query变量

在注册rides自定义文章类型时,显式指定query_var参数值,确保WordPress能正确识别该查询变量:

$args = array(
    // 其他参数保持不变
    "query_var" => "rides", // 显式指定query变量名
);
register_post_type("rides", $args);

(3)强制刷新重写规则缓存

修改代码后,登录WordPress后台进入设置→固定链接,无需修改任何设置,直接点击「保存更改」,强制刷新重写规则缓存。

修改后的完整插件代码

<?php

/*
Plugin Name: Etc etc.
*/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

function fun_be_post_type()
{
    $labels = array(
        'name'               => _x('Events', 'post type general name'),
        'singular_name'      => _x('Event', 'post type singular name'),
        'add_new'            => _x('Add New', 'track'),
        'add_new_item'       => __('Add New Event'),
        'edit_item'          => __('Edit Event'),
        'new_item'           => __('New Event'),
        'all_items'          => __('All Events'),
        'view_item'          => __('View Event'),
        'search_items'       => __('Search Events'),
        'not_found'          => __('No events found'),
        'not_found_in_trash' => __('No events found in the Trash'),
        'menu_name'          => 'Events'
    );
    $args = array(
        'labels'        => $labels,
        'rewrite' => array(
            'slug' => 'events',
            'with_front' => false
        ),
        'hierarchical' => true,
        'description'   => 'Holds our bike events and event-specific data',
        'public'        => true,
        'publicly_queryable' => true,
        'show_in_rest'  => true,
        'query_var'     => true,
        'capability_type'    => 'post',
        'map_meta_cap' => true,
        'rest_controller_class' => 'WP_REST_Posts_Controller',
        'menu_position' => 5,
        'menu_icon'     => 'data:image/svg+xml;base64,PHN2ZyB3etc...+',
        'supports'      => array('title', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields'),
        'has_archive'   => true,
        'autop'         => false
    );
    register_post_type('events', $args);

    $labels = array(
        "name" => "Rides",
        "singular_name" => "Ride",
    );

    $args = array(
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "show_ui" => true,
        "has_archive" => true,
        "show_in_menu" => true,
        'menu_position' => 6,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        'hierarchical' => false,
        "rewrite" => array("slug" => "events/%event%", "with_front" => false),
        "query_var" => "rides",
        "supports" => array("title", "revisions", "thumbnail")
    );

    register_post_type("rides", $args);
}
add_action('init', 'fun_be_post_type');


add_action('add_meta_boxes', function () {
    add_meta_box('rides-parent', 'Events', 'rides_attributes_meta_box', 'rides', 'side', 'default');
});

function rides_attributes_meta_box($post)
{
    $pages = wp_dropdown_pages(array('post_type' => 'events', 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('(no parent)'), 'sort_column' => 'menu_order, post_title', 'echo' => 0));
    if (! empty($pages)) {
        echo $pages;
    }
}

add_action('init', function () {
    add_rewrite_rule('^events/([^/]+)/([^/]+)/?$', 'index.php?rides=$matches[2]', 'top');
});

add_filter('post_type_link', function ($link, $post) {
    if ('rides' == get_post_type($post)) {
        if ($post->post_parent) {
            $parent = get_post($post->post_parent);
            if (!empty($parent->post_name)) {
                return str_replace('%event%', $parent->post_name, $link);
            }
        }
    }
    return $link;
}, 10, 2);

add_filter('manage_rides_posts_columns', 'set_custom_edit_br_columns');

function set_custom_edit_br_columns($columns)
{
    $columns = array(
        'cb' => $columns['cb'],
        'title' => __('Title'),
        'parent_id' => __('Event'),
        'date' => __('Date'),
    );

    return $columns;
}

add_action('manage_rides_posts_custom_column', 'custom_br_column', 10, 2);
function custom_br_column($column, $post_id)
{
    switch ($column) {
        case 'parent_id':
            $post_parent = get_post_parent($post_id);
            if ($post_parent) {
                $parent_title = get_the_title($post_parent);
                $parent_view_link = get_permalink($post_parent);
                $parent_edit_link = get_edit_post_link($post_parent);
                echo "
                    <a class='row' href='" . $parent_edit_link . "' aria-label='" . $parent_title . " (Edit)'>" . $parent_title . "</a>
                    
                    <div class='row-actions'><span class='edit'><a href='" . $parent_edit_link . "' aria-label='Edit “" . $parent_title . "”'>Edit</a> | </span><span class='view'><a href='" . $parent_view_link . "' rel='bookmark' aria-label='View “" . $parent_title . "”'>View</a></span></div>
                ";
            }
            break;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 06:25:56