在开发WordPress主题的过程中,经常要判断当前页面是否为首页。
执行首页判断的函数有两个,is_home()和is_front_page()。两者之间有一些微妙的差异,在官方文档中有比较详细的说明。不过,我更愿意用实际例子来说明,并记录下来,供自己参考。
前置步骤
为演示楚这两个函数在不同URL之间的行为,我在Tweentyseventy主题的footer.php内添加了以下php片段。
<?php if (is_front_page()):?> <span>is_front_page: true</span> <?php else:?> <span>is_front_page: false</span> <?php endif; ?> <?php if (is_home()):?> <span>is_home: true</span> <?php else:?> <span>is_home: false</span> <?php endif; ?>
建立两个Page类型的页面,Home和Blog,如下图。
测试默认首页设置
点击customize按钮,再进入Homepage Settings选项卡。将Your homepage displays设置为Your latest posts,如下图。
访问博客首页,结果如下。
is_front_page: true is_home: true
访问其他任何页面,两者的结果都是false。
测试自定义首页设置
接下来,将Your homepage displays设置为A static page,此时会出现额外的两个子选项。将Homepage设置为Home页面,Posts page设置为Blog页面,如下图。
访问首页,结果如下。
is_front_page: true is_home: false
访问Blog页,结果如下。
is_front_page: false is_home: true
访问其他页面,结果如下。
is_front_page: false is_home: false
更多解释
函数is_home()和is_front_page()的定于位于wp-include\class-wp-query.php,如下。
class WP_Query { // ... public $is_home = false; // ... public function is_home() { return (bool) $this->is_home; } // ... public function is_front_page() { // most likely case if ( 'posts' == get_option( 'show_on_front') && $this->is_home() ) return true; elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) ) return true; else return false; } // ...
可见,is_front_page()调用is_home()。
默认的首页设置是”posts”,即show_one_front==”posts”。因此,如果URL在首页,is_home()为true,is_front_page()也为true。
自定义首页设置为静态页面,则show_one_front==”page”。因此,若(1)首页对应的页面已设置,即get_option( ‘page_on_front’ )返回一个id;且(2)该id确实对应一个页面,即$this->is_page( get_option( ‘page_on_front’ ) 返回true,则可确定is_front_page()为true。
is_home()的具体实现比较复杂,涉及到url解析的很多细枝末节。不过,以上已经演示过了,要判断很简单:(1)默认首页设置,则在博客首页返回true;(2)静态首页设置,访问Posts Page对应页面时返回true。