Display the name of the PHP template file being used to render each page in the WordPress admin bar, making it instant to identify which template file to edit.
add_action( 'admin_bar_menu', function ( WP_Admin_Bar $bar ): void {
global $template;
if ( is_admin() || ! current_user_can( 'manage_options' ) || empty( $template ) ) {
return;
}
$file = ltrim( str_replace( [ get_stylesheet_directory(), get_template_directory(), WP_PLUGIN_DIR ], '', $template ), '/' );
$bar->add_node( [
'id' => 'nahnu-current-template',
'title' => esc_html( 'Template: ' . $file ),
'meta' => [ 'title' => esc_attr( $template ) ],
] );
}, 999 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
When you’re working on a theme, the first question is often “which template file is WordPress using for this page?” This snippet shows the answer in the admin bar for administrators, on every front-end page.
WordPress stores the path of the template it chose in the global $template variable. The snippet adds an admin bar item on admin_bar_menu showing that path, shortened to be relative to your theme or plugins folder. Hover over it to see the full path.
The previous version linked the item to the Theme File Editor. That editor is turned off on many sites, including any that use our “Disable the Theme and Plugin File Editor” snippet, so the link led to an error. The file name is also escaped now before it’s shown.
On block themes, $template points to WordPress’s template-canvas.php, because the real templates are stored as blocks. The Site Editor shows which template a page uses on those themes.
Only administrators see the item, and only on the front end. It’s safe to leave on a live site, but you’ll usually only want it during development.
While logged in as an administrator, open a single post. The admin bar should show something like “Template: single.php”.