默认情况下,WordPress 会在网站的前页面上按时间倒序显示您最新的帖子。许多 WordPress 用户希望将静态前页面或欢迎页面作为前页面使用。这种“静态前页面”的外观对于希望在网站前页面展示静态或欢迎信息的用户来说很常见。

网站前页面的外观和感觉是基于用户的设置与 WordPress 主题的功能和选项相结合而形成的。

自定义前页面的模板层级

在站点的前页面,如果存在 front-page.php 模板文件,WordPress 将始终使用该文件。如果不存在 front-page.php,WordPress 将根据用户在 设置 > 阅读 > 前页面显示中的配置,确定使用哪个模板文件,具体如下:

自定义站点前页面模板

要创建自定义站点前页面模板,请在主题中包含以下任一内容:

自定义博客文章索引页面模板

要创建自定义博客文章索引模板,请在主题中包含以下内容:

  • home.php

仅使用 home.php 模板文件作为博客文章索引。不要出于以下两个原因而使用自定义页面模板(如 template-blog.php):

  1. 当静态前页面功能配置正确时,即使将“帖子页面”指定的页面对应的自定义页面模板进行了分配,WordPress 也不会使用该自定义页面模板来显示博客文章索引。WordPress 仅会使用 home.php 或 index.php。
  2. 当将自定义页面模板分配给除指定为“帖子页面”之外的静态页面时,博客文章索引循环的分页将无法正常工作。

上下文条件标签

is_front_page

条件标签 is_front_page() 检查是否正在显示站点前页面。当正在显示站点前页面时返回 true,无论“设置 > 阅读 ->前页面显示”是设置为“您最新的帖子”还是“静态页面”。

is_home

条件标签 is_home() 检查是否正在显示博客文章索引。当正在显示博客文章索引时返回 true:即当站点前页面正在显示且“设置 > 阅读 ->前页面显示”设置为“您最新的帖子”,或者当“设置 > 阅读 ->前页面显示”设置为“静态页面”,且“帖子页面”的值是当前显示的页面时。

当正在显示站点前页面,且“设置 > 阅读 ->前页面显示”设置为“您最新的帖子”时,is_front_page()和 is_home() 都将返回 true。

front-page.php 的配置

如果存在 front-page.php 模板文件,无论“设置 > 阅读 ->前页面显示”是设置为“静态页面”还是“您最新的帖子”,该模板文件都将在站点的前页面上使用。主题需要考虑到这两种选项,以便网站前页面可以显示静态页面或博客文章索引。有几种方法可以实现这一点。

在 front-page.php 中的条件显示

允许 front-page.php 为“设置 > 阅读 ->前页面显示”的两种选项(“静态页面”或“您最新的帖子”)都进行考虑的一种方法是在 front-page.php 本身中添加条件,使用 get_option( 'show_on_front' )、get_home_template()和 get_page_template()。

方法 1:直接在 front-page.php 中包含自定义内容:

if ( 'posts' == get_option( 'show_on_front' ) ) {
include( get_home_template() );
} else {
// Custom content markup goes here
}

方法 2:包含任何页面模板:
if ( 'posts' == get_option( 'show_on_front' ) ) {
include( get_home_template() );
} else {
include( get_page_template() );
}

过滤 frontpage_template

另一种允许网站前页面显示静态页面/自定义内容或博客文章索引的方法,而无需在 front-page.php 中添加条件代码,是通过向 functions.php 添加过滤器回调来 过滤 frontpage_template:

function themeslug_filter_front_page_template( $template ) {
return is_home() ? '' : $template;
}
add_filter( 'frontpage_template', 'themeslug_filter_front_page_template' );

此方法会导致 WordPress 在显示博客文章索引时完全绕过 front-page.php 模板文件。

为 front-page.php 添加自定义查询循环

如果 front-page.php 模板文件包含默认的 WordPress 循环,如下所示:

<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
// do something
endwhile; else:
// no posts found
endif;

该循环适用于分配给“设置 > 阅读 ->帖子页面”的静态页面的帖子内容。

要显示自定义循环(最新博客文章、自定义/特色内容等),请使用对 WP_Query 的调用来添加次要循环查询。例如,要显示最新的 3 篇博客文章:

$latest_blog_posts = new WP_Query( array( 'posts_per_page' => 3 ) );

if ( $latest_blog_posts->have_posts() ) : while ( $latest_blog_posts->have_posts() ) : $latest_blog_posts->the_post();
// Loop output goes here
endwhile; endif;

分页

静态前页面不打算进行分页。WordPress 的 上一页 / 下一页链接函数都不适用于静态前页面。静态前页面的分页使用 page 查询变量,而不是 paged 变量。有关详细信息请参阅WP_Query。