is_home()
云策文档标注
概述
is_home() 是 WordPress 的条件标签函数,用于判断当前查询是否为博客主页(即文章索引页)。其行为依赖于“阅读设置”中的“首页显示”选项,区分静态首页和博客文章页。
关键要点
- is_home() 返回布尔值,表示查询是否为博客主页(文章索引页)。
- 与 is_front_page() 区分:is_home() 针对博客文章索引,is_front_page() 针对网站首页,两者可能重叠或分离,取决于“show_on_front”选项设置。
- 依赖于全局 $wp_query 对象,不能在“parse_query”动作前使用,否则会触发 _doing_it_wrong() 警告。
- 行为受选项值影响:get_option('show_on_front')('posts' 或 'page')、get_option('page_on_front')(静态首页页面ID)、get_option('page_for_posts')(博客文章页页面ID)。
代码示例
if ( is_home() ) {
// 这是博客文章索引页
get_sidebar( 'blog' );
} else {
// 这不是博客文章索引页
get_sidebar();
}注意事项
- 在 WordPress 2.1 引入静态首页功能后,博客文章索引和网站首页被视为不同的查询上下文。
- 使用前需确保查询已运行,避免在早期钩子中调用。
原文内容
Determines whether the query is for the blog homepage.
Description
The blog homepage is the page that shows the time-based blog content of the site.
is_home() is dependent on the site’s “Front page displays” Reading Settings ‘show_on_front’ and ‘page_for_posts’.
If a static page is set for the front page of the site, this function will return true only on the page you set as the “Posts page”.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
See also
Source
function is_home() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
return false;
}
return $wp_query->is_home();
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
znowebdev
The following example can be used in your sidebar to display different content when displaying the blog posts index.
if ( is_home() ) { // This is the blog posts index get_sidebar( 'blog' ); } else { // This is not the blog posts index get_sidebar(); }