如何处理WordPress仅post_id的URL:重定向或返回404避免重复内容
解决WordPress单页URL重复问题
需求1:将/%post_id%/重定向至/%post_id%/%postname%/
推荐使用WordPress内置钩子实现,无需修改服务器配置,兼容性更好:
在主题的functions.php文件(或自定义插件)中添加以下代码:
add_action('template_redirect', 'redirect_post_id_to_full_permalink'); function redirect_post_id_to_full_permalink() { global $wp; // 匹配仅由数字组成的请求路径(即单独的post_id) if (preg_match('/^(\d+)\/$/', $wp->request, $matches)) { $post_id = intval($matches[1]); $target_post = get_post($post_id); // 仅对已发布的文章执行重定向 if ($target_post && $target_post->post_status === 'publish') { $full_permalink = get_permalink($post_id); // 301永久重定向,传递SEO权重 wp_redirect($full_permalink, 301); exit; } } }
说明:
- 该代码会在页面加载前检查请求URL,若为单独的post_id路径,自动跳转到带postname的完整永久链接。
- 使用301重定向而非302,确保搜索引擎将权重转移到正确URL,避免重复内容惩罚。
需求2:让/%post_id%/返回404状态码
同样通过template_redirect钩子实现,直接触发404页面:
添加以下代码到functions.php:
add_action('template_redirect', 'send_404_for_post_id_only'); function send_404_for_post_id_only() { global $wp, $wp_query; // 匹配仅由数字组成的请求路径 if (preg_match('/^(\d+)\/$/', $wp->request, $matches)) { $post_id = intval($matches[1]); $target_post = get_post($post_id); if ($target_post && $target_post->post_status === 'publish') { // 设置404状态码和查询状态 $wp_query->set_404(); status_header(404); // 加载主题的404模板 get_template_part('404'); exit; } } }
说明:
- 访问单独的post_id URL时,系统会返回标准404页面和正确的404状态码,搜索引擎会将该URL标记为无效,不会收录重复内容。
注意事项
- 修改
functions.php前请备份文件,建议使用子主题添加代码,避免主题更新导致代码丢失。 - 若使用缓存插件,修改后需清除缓存才能生效。
- 两个需求二选一即可,不要同时启用两段代码。
内容的提问来源于stack exchange,提问作者Pedram Nasertorabi
相关产品推荐
相关产品推荐

