函数
is_page_template( string|array $template = '' )
描述
该WordPress函数可 判断当前位置是否在某个特定的页面模板中
参数
$template,(string|array),(可选)要匹配的特定模板文件名或模板数组。
返回值
(bool),成功则为真,失败则为假。
划重点
子目录中的页面模板
如果页面模板位于主题的子目录中(自WP 3.4起),需要在模板名称前加上文件夹名称和斜杠,例如:
is_page_template( 'page-templates/about.php' );
不能在循环内使用
由于在循环过程中某些全局变量会被覆盖,因此is_page_template()无法使用。为了在循环之后使用它,必须在循环之后调用wp_reset_query()。
页面模板存储在post_meta中,可以直接查询post_meta判断是否已为页面分配了页面模板。
相关函数
get_page_template_slug( int|WP_Post $post = null )
// in the loop:
if ( get_page_template_slug( get_the_ID() ) ){
// Yep, this page has a page template
}
// anywhere:
if ( get_page_template_slug( $some_post_ID ) ){
// Uh-huh.
}
函数更新
| 版 | 描述 |
|---|---|
| 4.7.0 | 现在可以使用任何帖子类型,而不仅仅是页面。 |
| 4.2.0 | 该$template参数已更改为也接受页面模板数组。 |
| 2.5.0 | 介绍了。 |
来源
文件:wp-includes/post-template.php
示例
if ( is_page_template( 'about.php' ) ) {
// about.php is used
} else {
// about.php is not used
}
如果页面模板位于文件夹中,则可以使用以下内容:
if ( is_page_template( 'wpmi_cn_template/page-about.php' ) ) {
// about.php is used
} else {
// about.php is not used
}
通过传递模板名称数组来指定多个模板。
if ( is_page_template( array( 'template-full-width.php', 'template-product-offers.php' ) ) ) {
// Do Something here if either of the above templates are being used
}
else {
// Else do this
}