正如我们在模板层次结构视图中看到的,index.php 是所有其他模板的默认备胎。因此,如果主题中,没有添加更具体的模板文件,那么,最后默认使用的就是index.php模板。

因此,我们希望将 index.php 模板文件写的非常的通用。

简要回顾一下,如果我们再次查看模板层次结构,我们可以看到:从左到右模板文件变得越来越通用,从右到左,会变得越来越定制化





WordPress模板层次06:index.php_ide



​index php xuhss.com01 - WordPress模板层次06:index.php​



实际上,一个抽象后的index.php文件就像这样:

            <?php get_header(); ?>/***页头***/
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>/***循环遍历***/
<?php the_title(); ?>/***标题***/
<?php the_content(); ?>/***内容***/
<?php get_sidebar(); ?>/***侧边栏***/
<?php get_footer(); ?>/***页尾***/

如果进入主题的代码并打开了index.php文件,可以看到它很简单。




WordPress模板层次06:index.php_ide_02



​index php xuhss.com02 - WordPress模板层次06:index.php​



<?php get_header(); ?>/***页头***/
<div class="container" role="main">
<div class="row">
<div class="col-md-8">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>/***循环遍历***/

<div class="page-header">
<h1><?php the_title(); ?></h1>/***标题***/
</div>
<?php the_content(); ?>/***内容***/
<?php endwhile; else: ?>
<div class="page-header">
<h1>Oh no!</h1>
</div>
<p>We could not find this page!!!</p>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>/***侧边栏***/
</div>
</div>
<?php get_footer(); ?>/***页尾***/

我们看到它调用get_header()和get_footer(),

我们将在稍后讲解这两个函数。但是显而易见,他们就是分别调用header.phpfooter.php文件。

这是一个很好的通用index.php例子。它就是这么通用。

因为我们不知道网站上可能会使用什么页面,我们必须放一些非常通用的东西,基本上只是标题和内容。