子比主题教程:访问不存在的链接时自动跳转回首页

问题场景当用户访问您网站上一个不存在的页面时(例如 您的域名/888),默认会显示“Not Found”错误。本教程将教您如何让这类错误页面自动跳转到网站首页。

实现效果

  1. 页面停留 10 秒后自动跳转到首页。

  2. 提供“立即返回首页”的按钮。

  3. 随机推荐 5 篇文章,提升用户体验。

一、操作步骤

  1. 备份原文件(重要!)
    通过 FTP 或主机文件管理器,进入路径 /wp-content/themes/zibll/,找到 404.php 文件。将其复制一份并重命名为 404_backup.php,以便出问题时可以快速恢复。

  2. 替换文件内容
    使用代码编辑器打开原来的 404.php 文件,删除全部原有内容,并粘贴以下代码:

<?php
// 这是一个自定义的404页面,带有自动跳转和随机文章推荐功能
get_header();
?>
<div class="container">
    <div class="text-center" style="padding: 60px 0 40px 0;">
        <div style="font-size: 100px; color: #ddd; margin-bottom: 20px;">
            <i class="fa fa-compass"></i>
        </div>

        <h2 class="error-title" style="margin-bottom: 20px;">🙈 页面飘走了~</h2>

        <p style="font-size: 16px; color: #666; margin-bottom: 30px;">
            您访问的页面(<span id="error-url" style="color:#ff5a5f;"></span>)不存在或已被移除。
        </p>

        <p id="countdown-msg" style="font-size: 14px; color: #999; margin-bottom: 30px;">
            页面将在 <span id="countdown-num" style="font-weight: bold; color: #ff5a5f;">10</span> 秒后自动跳转至 <a href="<?php echo home_url(); ?>" style="color:#07c;">首页</a>...
        </p>

        <a href="<?php echo home_url(); ?>" class="btn btn-primary" style="margin-bottom: 50px; padding: 8px 30px;">
            <i class="fa fa-home"></i> 立即返回首页
        </a>
    </div>

    <?php
    // 获取5篇推荐/最新文章
    $recommend_posts = new WP_Query(array(
        'posts_per_page'      => 5,        // 显示5篇文章
        'ignore_sticky_posts' => 1,        // 忽略置顶文章
        'orderby'             => 'rand',   // 随机排序
        // 如果你想显示最新文章而不是随机,把上面 'rand' 改成 'date' 即可
    ));

    if ($recommend_posts->have_posts()) :
    ?>
    <div class="recommend-section" style="max-width: 800px; margin: 0 auto 60px auto; border-top: 1px solid #eee; padding-top: 40px;">
        <h3 class="section-title" style="text-align: center; margin-bottom: 30px; font-size: 20px;">
            <i class="fa fa-thumbs-up"></i> 你可能感兴趣的文章
        </h3>
        <div class="row">
            <?php while ($recommend_posts->have_posts()) : $recommend_posts->the_post(); ?>
                <div class="col-md-6 col-sm-12" style="margin-bottom: 20px;">
                    <div class="recommend-item" style="background: #f8f9fa; border-radius: 8px; padding: 15px; transition: all 0.3s; height: 100%;">
                        <?php if (has_post_thumbnail()) : ?>
                            <div class="recommend-thumb" style="margin-bottom: 12px;">
                                <a href="<?php the_permalink(); ?>" style="display: block; overflow: hidden; border-radius: 6px;">
                                    <?php the_post_thumbnail('thumbnail', array('style' => 'width: 100%; height: auto; transition: transform 0.3s;', 'alt' => get_the_title())); ?>
                                </a>
                            </div>
                        <?php endif; ?>
                        <h4 class="recommend-title" style="margin: 0 0 10px 0; font-size: 16px; line-height: 1.4;">
                            <a href="<?php the_permalink(); ?>" style="color: #333; text-decoration: none;">
                                <?php the_title(); ?>
                            </a>
                        </h4>
                        <div class="recommend-excerpt" style="font-size: 13px; color: #666; line-height: 1.5;">
                            <?php echo wp_trim_words(get_the_excerpt(), 20, '...'); ?>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    </div>
    <?php
        // 重置文章查询,避免影响其他循环
        wp_reset_postdata();
    endif;
    ?>
</div>

<script type="text/javascript">
    // 显示当前访问的错误链接
    var errorUrlSpan = document.getElementById('error-url');
    if (errorUrlSpan) {
        errorUrlSpan.innerText = window.location.href;
    }

    // 倒计时时间(10秒)
    var totalSeconds = 10;
    var countdownElement = document.getElementById('countdown-num');
    var timer = null;
    var startTime = null;
    var remainingTime = totalSeconds;
    var isPageVisible = true;

    // 更新倒计时显示
    function updateDisplay(seconds) {
        if (countdownElement) {
            countdownElement.innerText = seconds;
        }
        if (seconds <= 0) {
            if (timer) {
                cancelAnimationFrame(timer);
                timer = null;
            }
            window.location.href = "<?php echo home_url(); ?>";
        }
    }

    // 核心计时函数(基于 requestAnimationFrame,不受滑动卡顿影响)
    function startCountdown() {
        if (timer) {
            cancelAnimationFrame(timer);
        }
        startTime = performance.now();
        remainingTime = totalSeconds;
        
        function step(now) {
            var elapsed = (now - startTime) / 1000;
            var newRemaining = Math.max(0, totalSeconds - Math.floor(elapsed));
            
            if (newRemaining !== remainingTime) {
                remainingTime = newRemaining;
                updateDisplay(remainingTime);
            }
            
            if (remainingTime > 0) {
                timer = requestAnimationFrame(step);
            } else {
                timer = null;
            }
        }
        
        timer = requestAnimationFrame(step);
    }

    // 监听页面可见性变化
    function handleVisibilityChange() {
        if (document.hidden) {
            if (timer) {
                cancelAnimationFrame(timer);
                timer = null;
            }
        } else {
            if (remainingTime > 0) {
                startCountdown();
            }
        }
    }

    // 开始倒计时
    startCountdown();
    
    // 监听页面可见性变化
    document.addEventListener('visibilitychange', handleVisibilityChange);
    
    // 防止手机滑动时浏览器默认行为影响JS执行
    document.body.addEventListener('touchmove', function(e) {
        // 空函数,仅用于确保JS在滑动时保持活跃
    }, { passive: true });
</script>

<style>
    /* 手机端适配:让推荐文章在小屏幕上单列显示 */
    @media (max-width: 768px) {
        .recommend-item {
            margin-bottom: 15px;
        }
        .col-md-6 {
            width: 100%;
        }
    }
    /* 鼠标悬停效果 */
    .recommend-item:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        background: #fff !important;
    }
    .recommend-item:hover .recommend-thumb img {
        transform: scale(1.05);
    }
</style>

<?php get_footer(); ?>

  1. 保存文件:完成粘贴后,保存并上传覆盖原文件。

二、服务器配置检查

为确保子比主题的 404 页面能正常生效,需根据您的服务器环境进行以下检查:

  • 如果您使用宝塔面板
    进入网站「设置」→ 「配置文件」,找到类似 #error_page 404 /404.html; 的行,在该行前面加上 # 将其注释掉(或直接删除整行),然后保存。

  • 如果您使用 Nginx / IIS 环境
    请确保错误页面的 404 指向不是一个固定的 /404.html 文件。只有取消服务器级别的硬性指向,才能让 WordPress 和子比主题接管 404 页面的显示。

三、测试效果

完成以上全部操作后,在浏览器中访问一个您网站上不存在的页面(例如 您的域名/abcde),验证是否能正常显示新的 404 页面,并在 10 秒后自动跳转到首页。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容