404 页面

在主题中添加一个404页面是很重要的,以防用户偶然发现一个不存在或尚未创建的页面。同样重要的是,你的404页面要给访问者提供一个到达正确位置的方法。

接下来的几个步骤将帮助你为WordPress主题建立一个有用的404页面。

创建 404.php 文件

由于404.php文件用于未找到页面的错误,第一步是创建一个名为404.php的文件并将其添加到你的WordPress主题文件夹。

通常情况下,404.php的一个伟大起点是你的index.php

 

添加文件头部

要使用主题的header.php文件,打开你的404.php文件,在顶部,添加一个描述:该文件是什么,并确保引入你的主题的页眉。

例如:

/**
 * The template for displaying 404 pages (Not Found)
 */
get_header();

 

为404页面添加正文

为了使404页面发挥作用,你必须在模板中添加主体内容。

示例:

<div id="primary" class="content-area">
        <div id="content" class="site-content" role="main">

            <header class="page-header">
                <h1 class="page-title"><?php _e( 'Not Found', 'twentythirteen' ); ?></h1>
            </header>

            <div class="page-wrapper">
                <div class="page-content">
                    <h2><?php _e( 'This is somewhat embarrassing, isn’t it?', 'twentythirteen' ); ?></h2>
                    <p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentythirteen' ); ?></p>

                    <?php get_search_form(); ?>
                </div><!-- .page-content -->
            </div><!-- .page-wrapper -->

        </div><!-- #content -->
    </div><!-- #primary -->

这个例子来自WordPress自带的Twenty Thirteen主题。在404页面中添加了一些文字和一个搜索表单。

你可以添加自己的文本,使你的404页面看起来更好。

 

创建404页面的最后一步是添加页脚。如果你愿意,你也可以添加一个侧边栏。

例如:

get_sidebar();
get_footer();

现在,您有了一个功能强大的404页面,其中包含一个搜索表单和一些文本,以防用户无意中发现错误的页面。一旦你确定了404.php已经上传,您可以测试404页面,只需键入不存在URL地址,你可以试试http://example.com/fred.php,这肯定会导致404错误,除非您实际有一个名为fred.php的文件。