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

WordPress functions.php重定向代码如何加5秒延迟同路径跳转

WordPress文章页5秒延迟跳转实现代码

修改说明

原代码使用PHP的header()函数实现服务端即时跳转,这种方式由服务器直接返回跳转响应,浏览器收到后会立刻跳转,无法实现停留等待效果。修改后的方案改用前端meta刷新规则实现5秒延迟跳转,同时增加访客友好提示,仅对文章类型(post)的详情页生效,不影响站点其他页面访问。

使用方法

  • 打开旧站主题的functions.php文件,删除原有即时跳转的代码
  • 复制下方完整代码粘贴到文件中
  • 将代码里的新站域名替换为你自己的目标站点域名即可

可直接使用的完整代码

function delay_redirect_old_posts() {
    global $post;
    // 仅在访问单篇文章详情页时触发跳转
    if (is_singular('post') && $post->post_type === 'post') {
        // 请将下方域名替换为你的新站域名,末尾不要加斜杠
        $new_site_base = 'https://www.OtherWebSite.com';
        $target_jump_url = $new_site_base . '/' . $post->post_name;
        
        // 输出带5秒延迟跳转的提示页面
        echo '<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 核心配置:5秒后自动跳转到对应新页面 -->
    <meta http-equiv="refresh" content="5;url=' . esc_url($target_jump_url) . '">
    <title>页面跳转提示</title>
    <style>
        .notice-wrap{max-width: 560px;margin: 22vh auto 0;padding: 0 20px;text-align: center;font-family: system-ui, "Microsoft Yahei", sans-serif;}
        .countdown-num{color: #2271b1;font-weight: 700;}
        .manual-link{color: #2271b1;}
    </style>
</head>
<body>
    <div class="notice-wrap">
        <h3>内容已迁移至新站点</h3>
        <p><span class="countdown-num">5</span> 秒后将自动跳转到对应新页面,若未自动跳转可 <a class="manual-link" href="' . esc_url($target_jump_url) . '">点此手动访问</a></p>
    </div>
    <script>
        let remain = 5;
        const countEl = document.querySelector('.countdown-num');
        const countTimer = setInterval(() => {
            remain--;
            countEl.textContent = remain;
            if (remain <= 0) clearInterval(countTimer);
        }, 1000);
    </script>
</body>
</html>';
        exit; // 终止旧站原有页面内容加载
    }
}
add_action('template_redirect', 'delay_redirect_old_posts', 1);

注意事项

  • 替换域名时不要在末尾加斜杠,避免出现双斜杠的路径错误
  • 代码保留了手动跳转入口,兼容极少数不支持meta自动刷新的浏览器场景
  • 跳转逻辑仅对默认文章类型生效,不会影响自定义文章类型、页面、分类归档等其他站点内容

内容的提问来源于stack exchange,提问作者Kathryn Laventure

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:57:34