Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Karen Vartapetov
Karen Vartapetov
22,567 Points

How to add CSS file on a specific page template via functions.php?

Need to add some extra css for specific page template like 'page-contacts.php', but adding body class is not an option, too many css rules to add. Want to do it via functions.php. Is it possible?

4 Answers

Karen Vartapetov
Karen Vartapetov
22,567 Points

No it does not work. And I've checked with Query Monitor is_page_template does not trigger. Perhaps because it does not see this page-contacts.php as template file - when you write in the top /*Template Name : Some Template Name */ and then choose in editor in Template dropdown. Instead is_page is triggered and is_single . And in body class there is page-template-default class, so WordPress is_page_template will not work anyway. is_page works great while page name fits.

Thanks for help! =)

Kevin Korte
Kevin Korte
28,149 Points

Sure something like this in your function file would work

<?php
if( is_page_template( 'page-contacts.php') {
  wp_enqueue_style( 'my-page-contacts-css', '/path/to/style.css')
}

Now that css file will only be included on the page-contacts.php page template.

Karen Vartapetov
Karen Vartapetov
22,567 Points

I don't know why, but is_page_template is not working. Should I write some comment section in the top of the template php file something to specify that this is the specific template like:

/*Template Name: Contacs Page*/

By the way I've tried this also, but still not working

Karen Vartapetov
Karen Vartapetov
22,567 Points

UPDATE:

I've found the solution to use is_page('contacts'), then it triggers the code. But still wondering why is_page_template is not working for me. Is there any chance to debug this?

Kevin Korte
Kevin Korte
28,149 Points

You can throw in an echo get_page_template() and it'll tell you what page template it's using. See if it comes back as page-contacts.php

Karen Vartapetov
Karen Vartapetov
22,567 Points

it comes with a full path to file page-contacts.php

C:\xampp\htdocs\energy/wp-content/themes/Energy/page-contacts.php

here it is

Kevin Korte
Kevin Korte
28,149 Points

So curiosity, does is_page_template('C:\xampp\htdocs\energy/wp-content/themes/Energy/page-contacts.php'); work?