Can't use is_page_template in lib/scripts.php

As I just explained in issue 1156 (feel free to close if irrelevant):

In order to load a custom stylesheet only for pages matching a certain template, I’ve been trying to append the following code at the end of the roots_scripts function in lib/scripts.php:

if (is_page_template('my-template.php')) {
  wp_enqueue_style('custom', get_template_directory_uri() . "custom-style.css", false, null);
}

Loading the stylesheet without the conditional statement works, but it seems is_page_template returns false even though I verified that I’m performing the check on the right template via basename(get_page_template()).

I know I could circumvent this by loading the stylesheet via a custom header file, but the aforementioned method feels neatter and more in line with the DRY principles.

Any clue on what’s going on there?

Yes, you’re using is_page_template() incorrectly. See here: http://codex.wordpress.org/Function_Reference/is_page_template#Page_template_in_subdirectory

Well @cfx, I read through the doc one more time, but could you tell me what you find incorrect in the code of the original post? The relevant template is not located in any subdirectory (just along all the other base-.php and page-.php files).

Could it be that it’s too early is the initialisation stack for this function to be available in lib/scripts.php? Or I am missing something obvious?

Take a look at the WP function you’re calling: https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/post-template.php#L1597

along with the function it in turn relies on: https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/post-template.php#L1624

get_page_template() and is_page_template() sound deceptively similar but they are subtly different because the “Page Template” is different from the “page template file.” Admittedly, the WP documentation could be better for these two functions.

You can see (here) that if you add this to my-template.php it will echo the correct $template argument you need to use for is_page_template():

echo get_post_meta(get_queried_object_id(), '_wp_page_template', true);

The big problem is if your custom template files rely on the WP template hierarchy instead of a custom Page Template then get_page_template_slug() will return an empty string which will cause is_page_template() to return false every time.

So, either change the Page Template you’re using, or if your new page doesn’t use a custom Page Template because it relies on the default WP template hierarchy then just use the original function you used to get the template file’s basename in your if():

if(basename(get_page_template()) == 'my-template.php') {
  wp_enqueue_style('custom', get_template_directory_uri() . "custom-style.css", false, null);
}
1 Like