• Hi everyone,

    I’m trying to retrieve the current page’s template name the same way it’s shown in the Block Editor. In the editor, I can get it using:

    wp.data.select('core/edit-site').getEditedPostId();

    For example, it returns:

    • Blog Home template: "twentytwentyfour//home"
    • Single Posts template: "twentytwentyfour//single"
    • Pages template: "twentytwentyfour//page"

    However, when trying to get the template name via PHP, I haven’t found a reliable way.
    I’ve tried several approaches, but global $template always returns:

    /opt/web/public/wp-includes/template-canvas.php

    Regardless of the hook I use.

    Is there a way to get the actual template name in PHP, similar to how it’s retrieved in the Block Editor?

    Any help is appreciated!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Tércio Tales

    (@terciotales)

    I also noticed that the template name appears in the <body> class, like this:

    page-template page-template-page-noticias page page-id-704 logged-in admin-bar wp-custom-logo wp-embed-responsive noptin customize-support

    I need a way to get that page-template-page-noticias using PHP. Is there a function to retrieve this?

    Moderator bcworkz

    (@bcworkz)

    You can learn which classic theme’s PHP template is being used for any front end request via the “template_include” filter. I don’t know how block theme templates are managed, sorry. There may not be a direct PHP solution.

    For an indirect approach you can learn of all body class attributes via the “body_class” filter. But I believe the onus is upon the theme to stuff template class names into the passed array, so you’d want to hook with a large priority arg to help ensure the theme has done its thing first. It’s possible some themes do not bother to do this, so it’s not 100% reliable for all themes.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.