saber 酱的抱枕

Fly me to the moon

08/29
2015
学习

为WordPress制作404页面

我用的这个主题对404的处理不太好,它不经过任何提示,直接展示首页内容(没有跳转过程,所以地址栏的链接还保留着错误的链接)。所以我今天搜索了一番,做了自己的404页面。

本文内容适用于WordPress+Apache。

首先建立个404.php的文件,我的模板内容如下:

<?php get_header(); ?>
<div id="ctn">
    <div id="content">
        <div class="post_ctn">
        	<hgroup class="post_hctn">
        		<div class="post_h_l">
        			<h2 class="post_h"><a href="">Error:404 Not Found</a></h2>
        		</div>
        	</hgroup>
            <div class="post_t">
                <p><img src="/f/404.jpg" alt="404"></p>
                <p>诶?竟然给老娘弄出404?</p>
                <p style="font-weight: bold;font-size:20px;">如果您是从搜索结果点击进来看到的404,<a href="" id="toRight" style="font-weight: bold;text-decoration: underline;">您可以点击这里到达正确的页面</a></p>
                <script>
                if (location.href.indexOf(".html")==-1) {
                    $("#toRight").attr("href",location.href.substring(0, location.href.length-1).concat(".html"));
                };
                </script>
                <p>访问本站出现404,一般是因为以下原因:</p>
                <p>本站启用固定链接之后,搜索引擎未全面更新收录。所以有时候搜索结果里的文章链接是错误的。</p>
                <p>如果上面的链接仍然不正确,您可以搜索您需要的内容:</p>
                <?php get_search_form(); ?>
                <p>您也可以<a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">访问首页</a>,或给我<a href="/%e7%95%99%e8%a8%80#comment">留言</a>,告诉我问题的详细情况。</p>
            </div>
        </div>
    </div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

我用了文章页面的模板,把文章区域添上了自己的内容。如果你和我的模板不一样,参考主体部分就行了。

为了便于备份,我把404.php放到了模板目录中。你也可以放到网站根目录里。

到这里,你可以输入一个错误的网址试试,如果能出现404页面就OK了。如果不能,则需要编辑.htaccess文件,在WordPress规则的结束标记之前插入404指示:

# BEGIN WordPress
<IfModule mod_rewrite.c>
//......
</IfModule>
ErrorDocument 404 /wp-content/themes/clearisionchild/404.php
# END WordPress

注意,不要插入到其他规则(如上例中的IfModule规则)之中。

为WordPress制作404页面