描述
此模板标签允许您确定是否在页面模板中,您可以选择提供模板文件名或模板文件名数组,然后检查所指定的模板。
更多类似的主题函数信息,请查看主题开发手册中的条件标签文章。
参数
- $template
- 
(string|string[]) (可选) 要匹配的特定模板文件名或模板数组。 默认值: '' 
返回
(bool) 成功时为true,失败时为false。
说明
子目录中的页面模板
如果页面模板位于主题的子目录中(自WP 3.4起),请在模板文件名前加上文件夹名和斜杠,例如:
is_page_template( 'templates/about.php' );
不能在循环内使用
由于某些全局变量在循环期间被覆盖is_page_template()将不起作用。为了在循环后使用它,必须在循环后调用wp_reset_query()。
替代方案
由于页面模板slug存储在post_meta中,用于分配给页面模板的文章,因此可以直接查询post_meta以查看是否为给定页面分配了页面模板。这是is_page_template()内部使用的方法。
函数get_page_template_slug( $post_id )将返回当前分配的页面模板的slug(如果没有分配模板,则返回空字符串;如果$post_id与实际page不对应,则返回false)。您可以在任何地方(在循环中或外部)轻松使用它来确定是否为页面分配了页面模板。
  // 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 | 开始引入 | 
使用示例
- 如果页面模板位于目录中,则可以使用以下内容: - if ( is_page_template( 'directory-name/page-about.php' ) ) { // about.php is used } else { // about.php is not used }- 如果您正在使用多个页面模板,并且希望保持文件的条理化,这将非常有用。 
- 是否正在使用页面模板“about”?请注意,与其他条件不同,如果要指定特定的页面模板,则需要使用文件名,例如 - about.php或- my_page_template.php。- if ( is_page_template( '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 }
