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

如何处理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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:52:21