WordPress CPT添加分类到固定链接时普通文章404错误排查求助
问题根源
这个404错误是WordPress重写规则冲突导致的:
- 你设置了全局固定链接带
/%category%/前缀 - 注册自定义分类法和CPT时,没有设置
with_front = false,导致自定义内容的重写规则默认继承了全局前缀,优先级又高于普通文章的分类规则,访问普通文章时系统会错误匹配到自定义分类法的路由,找不到对应内容就返回404。
修复步骤
1. 修改CPT和分类法注册代码
修改后的完整代码如下:
/* Custom Post Type - Gallery */ // 调整钩子优先级为11,晚于WordPress默认规则注册 add_action( 'init', 'add_gallery_post_type', 11 ); function add_gallery_post_type() { register_post_type( 'zm_gallery', array( 'labels' => array( 'name' => __( 'The Gallery' ), 'singular_name' => __( 'The Gallery' ), 'add_new_item' => __( 'Add New Photograph' ), 'all_items' => __( 'All Images' ), ), 'public' => true, 'has_archive' => true, // rewrite参数添加with_front => false,不继承全局固定链接前缀 'rewrite' => array( 'slug' => 'gallery-item', 'with_front' => false ), 'supports' => array( 'title' ), 'menu_position' => 4, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'menu_icon' => 'dashicons-camera', 'capability_type' => 'post', ) ); } /* Gallery Taxonomies */ // 调整钩子优先级为11,晚于WordPress默认规则注册 add_action( 'init', 'be_register_taxonomies', 11 ); function be_register_taxonomies() { $taxonomies = array( array( 'slug' => 'location', 'single_name' => 'Location', 'plural_name' => 'Locations', 'post_type' => 'zm_gallery', ), array( 'slug' => 'circa', 'single_name' => 'Circa', 'plural_name' => 'Circas', 'post_type' => 'zm_gallery', ), array( 'slug' => 'era', 'single_name' => 'Era', 'plural_name' => 'Era', 'post_type' => 'zm_gallery', ), ); foreach ( $taxonomies as $taxonomy ) { $labels = array( 'name' => $taxonomy['plural_name'], 'singular_name' => $taxonomy['single_name'], 'search_items' => 'Search ' . $taxonomy['plural_name'], 'all_items' => 'All ' . $taxonomy['plural_name'], 'parent_item' => 'Parent ' . $taxonomy['single_name'], 'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':', 'edit_item' => 'Edit ' . $taxonomy['single_name'], 'update_item' => 'Update ' . $taxonomy['single_name'], 'add_new_item' => 'Add New ' . $taxonomy['single_name'], 'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name', 'menu_name' => $taxonomy['plural_name'], ); // rewrite参数添加with_front => false,不继承全局固定链接前缀 $rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'], 'with_front' => false ); $hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true; register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array( 'hierarchical' => $hierarchical, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => $rewrite, ) ); } }
2. 刷新重写规则
代码修改完成后,进入WordPress后台「设置」-「固定链接」页面,不需要修改任何配置,直接点击「保存更改」按钮,即可刷新系统的重写规则,普通文章的404问题就会解决。
内容的提问来源于stack exchange,提问作者Trishah
相关产品推荐
相关产品推荐

