1

Is There Any Way to get the template Name By full URL for example

If the full url is

www.example.com/hello-world

I need a function that return the template name (page.php)

I know that WordPress matches every url with regular expression to determine the query and decide which template to include.

That's exactly what I need, a built in or (custom made) function that takes the URL and returns back the corresponding template

3 Answers 3

2

You can make use of the global $template which holds the complete path of the current template being use to display a page. From there you can manipulate the value to get the name of the template

As example, the value of $template looks like this: (This is on my localhost on my PC)

E:\xammp\htdocs\wordpress/wp-content/themes/pietergoosen2014/page-test.php

To only return the page-test.php part, I use the following function which uses the PHP functions substr and strrpos which finds the last / character in URL and then returns everything after that:

function get_current_template() {
    global $template;
    return substr( $template, strrpos( $template, '/' ) + 1 );
}

You can then use it anywhere in your template like

echo get_current_template();

I usually just print the template name in my site's header on my localhost like

add_action( 'wp_head', function () 
{
    global $template;
    print substr( $template, strrpos( $template, '/' ) + 1 );
});

or

add_action( 'wp_head', function () 
{
    global $template;
    print $template;
});
1

You should be able to use get_page_template_slug()

And since that function requires an id instead of a URL, use url_to_postid() to find the ID first

1
  • i was hoping for a general function that works with all url your suggestion will only work for page and post url not for other url`s likes archive and search Commented Oct 2, 2015 at 23:28
0

Use the following code in header.php to know the current template:

<body id="<?php echo get_option('current_page_template'); ?>">

I'd be happy if this helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.