Reputation: 988
I'm trying to retrieve the filename/path of template used on the 'Edit Page'-page in the Dashboard.
Similar to what wp-includes/template-loader.php
(source) does on the front end: finding out which template to render.
Unfortunately, expressions like is_front_page()
- which Wordpress' template-loader.php
uses to find out if it should use get_front_page_template()
- don't work correctly on the admin page. Which is to be expected because those expression use the global $wp_query object, and not the current query.
What I've tried so far:
Running a post loop inside the admin page
$args = array(
'p' => get_the_ID(),
'post_type' => 'any'
);
$query = new \WP_Query($args);
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<?= the_title(); ?><br>
Is front page: <?= is_front_page() ? 'true' : 'false' ?>
<?php endwhile; endif; ?>
Displays:
Home
Is front page: false
Using get_post_meta
<?= get_post_meta(get_the_ID(), '_wp_page_template', true); ?>
Displays:
default
...which would be the same for front-page.php on Home and page.php on another default page, so this doesn't help me.
In short
What I'm trying to get is front-page.php
when I'm editing my 'Home' page. Or custom-template.php
when I'm editing some page with the custom template selected. Or about-page.php
when I'm editing a page called 'About'. How to get the correct filename or path?
Upvotes: 13
Views: 4704
Reputation: 7227
The only solution I found is this:
global $template;
echo basename($template); // front-page.php
I know it's ugly, but I just couldn't find a way to not use this global variable.
Upvotes: 0
Reputation: 608
If your specific problem is with the home page, you could use a combination of get_page_template()
and comparing the edited page's ID with get_option('page_on_front')
(see WordPress option reference). There's also an option, show_on_front
, which indicates whether the front page shows posts or a static page.
Maybe this helps? I don't know if there are other edge cases where a different template will be used...
Upvotes: 3
Reputation: 1508
Use get_page_template()
:
<?php echo realpath(get_page_template()); ?>
It outputs something like /foo/bar/baz/wp-content/themes/your-theme/{page-template}.php
You can choose not to use realpath()
and just get the template name.
Upvotes: 2