I am trying to create a CSS file that only works for one page template. I am trying to do it using wp enqueue style but to no avail so far.

I was able to get it to work (sort of) using the following in my header.php.

   <?php if( is_page_template('background-slider-template.php') ) { ?> 
    <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/background-slider-template.css" type="text/css" media="screen" />
    <?php } ?>

I know that is not the proper way to I tried the following using wp enqueue style.

function register_more_stylesheets() {
    wp_register_style( 'stylesheet_name', get_stylesheet_directory_uri() . '/styledtwentyfifteen/background-slider-template.css' );
function add_my_stylesheet() {
    if ( is_page_template( '/styledtwentyfifteen/background-slider-template.php' ) ) { // using page slug
    wp_enqueue_style( 'stylesheet_name', get_stylesheet_uri() . '/styledtwentyfifteen/background-slider-template.css');  // no brackets needed for one line and no else
add_action( 'init', 'register_more_stylesheets' ); // should I use wp_print_styles hook instead?
add_action( 'wp_enqueue_scripts', 'add_my_stylesheet' );

It didn't work at all, although I feel like I am close.

I don't know if this affects anything but I am using a Child theme of the Twenty Fifteen theme to do this.

Thanks in advance!

  • You have get_stylesheet_uri instead of get_stylesheet_directory_uri. – Milo Nov 5 '15 at 4:09

If "/styledtwentyfifteen" is your child directory then that's included by get_stylesheet_directory_uri() (of which bloginfo('stylesheet_directory') is an alias) so you should leave it out on registering:

function register_more_stylesheets() {
    wp_register_style( 'stylesheet_name', get_stylesheet_directory_uri() . '/background-slider-template.css' );

Similarly with is_page_template() you only need the file name (relative to the template directory), and if you register a style you should just use its handle when enqueuing:

function add_my_stylesheet() {
    if ( is_page_template( 'background-slider-template.php' ) ) { // using page slug
        wp_enqueue_style( 'stylesheet_name' );
  • Thanks, but for some reason this is not working. I have no idea why but it doesn't seem to work. I feel like I have tried every piece of code out there for this but none of them seem to work. – matthew Nov 5 '15 at 16:03
  • Oh that's disappointing, can't think what's going wrong. Still, at least the "header.php" method works for you (and it's not really that bad a way to do it really)... – bonger Nov 5 '15 at 16:53
  • 1
    Yes, that is working for me at least. I think it may be my theme and child theme that is causing the issue. Anyway, for now at least I have a way to achieve it. Thanks for your help. – matthew Nov 6 '15 at 2:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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