is_page_template() WordPress Function
The is_page_template() function in WordPress allows you to check if a particular page is using a specific page template. This can be useful if you want to target specific pages with custom code or styling.
is_page_template( string|string[] $template = '' ) #
Determines whether the current post uses a page template.
Contents
Description
This template tag allows you to determine if you are in a page template. You can optionally provide a template filename or array of template filenames and then the check will be specific to that template.
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
- $template
(string|string[])(Optional)The specific template filename or array of templates to match.
Default value: ''
Return
(bool) True on success, false on failure.
More Information
Page template in subdirectory
If the page template is located in a subdirectory of the theme (since WP 3.4), prepend the folder name and a slash to the template filename, e.g.:
is_page_template( 'templates/about.php' );
Cannot Be Used Inside The Loop
Due to certain global variables being overwritten during The Loop is_page_template()
will not work. In order to use it after The Loop you must call wp_reset_query() after The Loop.
Alternative
Since the page template slug is stored inside the post_meta for any post that has been assigned to a page template, it is possible to directly query the post_meta to see whether any given page has been assigned a page template. This is the method that is_page_template() uses internally.
The function get_page_template_slug( $post_id ) will return the slug of the currently assigned page template (or an empty string if no template has been assigned – or false if the $post_id does not correspond to an actual page). You can easily use this anywhere (in The Loop, or outside) to determine whether any page has been assigned a page template.
// 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. }
Source
File: wp-includes/post-template.php
function is_page_template( $template = '' ) { if ( ! is_singular() ) { return false; } $page_template = get_page_template_slug( get_queried_object_id() ); if ( empty( $template ) ) { return (bool) $page_template; } if ( $template == $page_template ) { return true; } if ( is_array( $template ) ) { if ( ( in_array( 'default', $template, true ) && ! $page_template ) || in_array( $page_template, $template, true ) ) { return true; } } return ( 'default' === $template && ! $page_template ); }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
4.7.0 | Now works with any post type, not just pages. |
4.2.0 | The $template parameter was changed to also accept an array of page templates. |
2.5.0 | Introduced. |