【问题标题】:How can I redirect users on the new 404 page without plugin?如何在没有插件的情况下在新的 404 页面上重定向用户?
【发布时间】:2026-01-13 21:45:02
【问题描述】:

我的主题中有一个 404 页面,但我没有使用该页面。我使用 wpbakery 页面构建器在 WordPress 中创建了一个新的 404 页面。我想知道如何在没有插件的情况下在新的 404 页面上重定向用户?

【问题讨论】:

标签: wordpress .htaccess redirect


【解决方案1】:

您可以使用插件404page

或者一些代码adapted from this plugin:

add_filter(
    '404_template',
    static function () {
        global $wp_query;

        $wp_query = new WP_Query();
        $wp_query->query('page_id='.$pageID);
        $wp_query->the_post();
        $template = get_page_template();
        rewind_posts();

        add_filter(
            'body_class',
            static function ($classes) {
                if (!in_array('error404', $classes, true)) {
                    $classes[] = 'error404';
                }

                return $classes;
            }
        );

        return $template;
    },
    999
);

【讨论】:

  • 非常感谢,这正是我要找的。​​span>
【解决方案2】:
  1. 在管理员中创建 404 页面。

  2. 为该页面创建自定义页面模板。

  3. 添加您的自定义 404 内容

  4. 在您的主题中打开 404.php 文件。

  5. 在该文件的顶部添加以下代码。

    header("HTTP/1.1 301 Moved Permanently");
    
    header("Location: ".home_url('/404page/'));
    
    exit();
    
  6. 尝试查找未找到的内容,您将被重定向到自定义 404 页面

另外,您可以尝试此操作挂钩以重定向到自定义 404 页面。将此代码放入您的 function.php 文件中。这是上面第 5 点的替换选项)

add_action( 'template_redirect', 'redreict_to_custom_404_page' );
function redreict_to_custom_404_page(){
    // check if is a 404 error
    if( is_404()  ){
        wp_redirect( home_url( '/404page/' ) );
        exit();
    }
}

或者如果你想用 WP bakery 创建 404 页面

  1. 创建一个私有 404 页面并在管理员中使用 WP bakery 构建。

  2. 打开404.php文件,通过以下代码获取404page的内容

     $page_id = 123; // 404page id
     $page    = get_post( $page_id );
     $content = $page->post_content;
     echo $content;
    

【讨论】:

  • 让我试试这个
  • 重定向到 404 页面是不好的,不要那样做。任何搜索引擎机器人等都不会再为最初请求的 URL 获得正确的 404 状态代码。
  • @CBroe,我对 404 页面有不同的设计,所以我在管理面板中创建一个页面并使用 wpbakery 构建页面。我必须重定向我的新 404 页面。
  • 那么你应该以某种方式使用 WP 提供的任何机制来做到这一点,但 使用外部重定向。
  • @NarenVerma 检查我的编辑。这不会影响您的 wp 404 机制。
最近更新 更多