重写自定义文章类型后其他页面及文章出现404错误求助
问题描述
我使用以下代码重写booking_spots自定义文章类型的URL别名:
function ns_update_booking_spot_cpt($args, $post_type){ if($post_type == 'booking_spots'){ $args['has_archive'] = true; $args['rewrite'] = array('slug' => '%sports-category%'); $args['with_front'] = false; } return $args; } add_filter('register_post_type_args', 'ns_update_booking_spot_cpt', 10, 2);
另外,我用下面的代码修改文章链接(其中“Location”是ACF字段名称):
add_filter( 'get_the_archive_title_prefix', '__return_false' ); function keep_product_link( $post_link, $id = 0 ) { $post = get_post($id); $custom_field_values = get_field( 'Location',$post->ID); $value = ""; foreach($custom_field_values as $custom_field_value ): $value = $custom_field_value; endforeach; if($custom_field_values){ return str_replace( '%sports-category%' , $value , $post_link ); } return $post_link; } add_filter( 'post_type_link', 'keep_product_link', 10, 2 );
保存固定链接设置后,booking_spots类型的文章能正常加载,但其他所有页面和文章都出现404错误,需要修复这个问题。
修复方案
出现404的核心原因是你设置的%sports-category%占位符和WordPress默认重写规则冲突,导致WordPress无法区分该结构对应的是自定义文章类型还是普通页面/文章。按以下步骤修复:
1. 限制链接修改仅作用于booking_spots类型
当前的keep_product_link函数会处理所有文章类型的URL,可能干扰其他页面的链接生成。修改函数,只针对booking_spots类型:
add_filter( 'get_the_archive_title_prefix', '__return_false' ); function keep_product_link( $post_link, $post ) { // 仅处理booking_spots类型的文章 if ( 'booking_spots' !== $post->post_type ) { return $post_link; } $custom_field_values = get_field( 'Location', $post->ID ); $value = ""; foreach($custom_field_values as $custom_field_value ): $value = $custom_field_value; endforeach; if($custom_field_values){ return str_replace( '%sports-category%' , $value , $post_link ); } return $post_link; } add_filter( 'post_type_link', 'keep_product_link', 10, 2 );
2. 添加自定义重写规则
需要明确告诉WordPress,当URL匹配/[location]/[post-slug]/结构时,应该指向booking_spots类型的文章,而非普通页面:
function ns_add_booking_spot_rewrite_rules() { // 正则匹配Location值(假设为纯文本,无斜杠)和文章别名 add_rewrite_rule( '^([^/]+)/([^/]+)/?$', 'index.php?post_type=booking_spots&name=$matches[2]', 'top' ); } add_action( 'init', 'ns_add_booking_spot_rewrite_rules' );
提示:如果Location字段存储的是分类ID、别名或其他格式,需要调整正则表达式和对应的查询参数。
3. 刷新重写规则
修改代码后,进入WordPress后台「设置」→「固定链接」,直接点击「保存更改」按钮(无需修改任何设置),触发重写规则的刷新。
额外优化建议
- 如果ACF的Location字段是单选类型,可以去掉
foreach循环,直接用$value = $custom_field_values;取值,简化代码。 - 为Location字段设置默认值(比如
default-location),避免字段为空时生成无效URL。
内容的提问来源于stack exchange,提问作者ANJANA vk
相关产品推荐
相关产品推荐

