Find out whether a template file is used by a page and get that page -Wordpress

I'm developing now a wordpress theme, and wondering if there is an option to know if a template file is being used by a page? I need the link to that page... thanks!

2 Answers

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.

is_page_template(); function will return true when template is used. you can also pass file name to check if particular template is applied or not.

if ( is_page_template('about.php') ) {
// Returns true when 'about.php' is being used.
} else {
// Returns false when 'about.php' is not being used.
}

There is one more method too. You can use get_post_meta to get value of applied template.

global $post;
get_post_meta($post->ID,'_wp_page_template',true);
1

The previously suggested answer will not get you what you want. It will just show you in the current page or a page you specify is using the template not find any pages that are using it.

If you want to actually search to see if any pages are using a template you can make a query. meta_query isn't the most efficient/fastest but depending on what you are building probably won't be an issue.

$query = new WP_Query( array( 'post_type' => 'page', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => 'your-template.php', ), ), ) );
if ( $query->have_posts() ) { /* There is a match so either start the loop and use get_the_permalink() to get the link or make a foreach loop and get the ids of the items and get_the_permalink($id) */
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like