using wp enqueue style to create a CSS file specifically for a page template

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!

Topic theme-twenty-fifteen wp-enqueue-style code child-theme php Wordpress

Category Web


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' );
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.