WordPress房产网站自定义固定链接后访问出现404,需配置正确的重写规则
WordPress房产网站自定义固定链接后访问出现404,需配置正确的重写规则
看起来你已经成功修改了房产页面的前端显示链接,但404的问题确实出在重写规则的配置上——当前的规则没办法让WordPress正确识别你修改后的URL对应的房产文章。我来帮你梳理问题并给出修复方案:
问题根源
你的自定义URL结构是property/2-4-king-street-sw1y6ql/,而你当前的重写规则^property/([^/]+)-([^/]+)/?$会把这个URL拆成$matches[1] = 2-4-king-street和$matches[2] = sw1y6ql,然后把$matches[1]传给name参数。但WordPress里对应的房产文章的原始name(slug)是2-4-king-street-london,系统找不到匹配的文章,自然返回404。
修复方案
我们需要调整重写规则,让它能正确捕获完整的URL后缀,再通过request过滤器根据邮编定位到对应的房产文章。修改后的完整代码如下:
add_filter( 'post_type_link', 'customise_property_post_type_link', 10, 4 ); function customise_property_post_type_link( $post_link, $post, $leavename, $sample ) { if ( get_post_type( $post->ID ) == 'property' ) { // Retrieve the postcode from the post meta $meta_data = get_post_meta( $post->ID ); $postcode = isset( $meta_data['_address_postcode'][0] ) ? sanitize_title( str_replace( '-', '', $meta_data['_address_postcode'][0] ) ) : ''; // Ensure a valid postcode is available if ( ! empty( $postcode ) ) { // Replace only the last word (after the final hyphen) with postcode $post_link = preg_replace( '/[^-]+\/$/', $postcode . '/', $post_link ); } } return $post_link; } add_action( 'init', 'rewrites_init' ); function rewrites_init() { // Add rewrite rule to capture the full custom slug add_rewrite_rule( '^property/([^/]+)/?$', 'index.php?post_type=property&custom_property_slug=$matches[1]', 'top' ); } add_filter( 'request', 'handle_custom_property_request' ); function handle_custom_property_request( $query_vars ) { // Check if we're dealing with a custom property slug if ( isset( $query_vars['custom_property_slug'] ) && isset( $query_vars['post_type'] ) && $query_vars['post_type'] == 'property' ) { $custom_slug = $query_vars['custom_property_slug']; // Extract the postcode from the end of the slug (after last hyphen) $postcode = substr( $custom_slug, strrpos( $custom_slug, '-' ) + 1 ); // Find property post with this postcode in meta $properties = get_posts( array( 'post_type' => 'property', 'meta_key' => '_address_postcode', 'meta_value' => str_replace( '-', '', $postcode ), // Match sanitized postcode 'posts_per_page' => 1, 'fields' => 'ids' ) ); if ( ! empty( $properties ) ) { // Replace custom slug with the actual post name (slug) $query_vars['name'] = get_post_field( 'post_name', $properties[0] ); unset( $query_vars['custom_property_slug'] ); } } return $query_vars; }
代码说明
- 优化了
post_type_link里的正则逻辑,更简洁地替换URL最后一段的末尾词为邮编; - 重写规则改为捕获完整的URL后缀,传递给自定义参数
custom_property_slug; - 通过
request过滤器从自定义slug中提取邮编,根据邮编查询对应房产文章,再将查询参数替换为文章的原始slug,让WordPress能正确加载内容。
操作步骤
- 将这段代码替换你当前的代码(放到主题的
functions.php或者自定义插件中); - 登录WordPress后台,进入「设置」→「固定链接」,直接点击「保存更改」(无需修改设置,这一步会刷新重写规则,确保新规则生效);
- 现在访问修改后的房产URL,应该就能正常加载页面了。
备注:内容来源于stack exchange,提问作者Dgeorgex000000
相关产品推荐
相关产品推荐

