Dynamically Load Styles and Scripts from Theme Functions.php

A couple issues here…

First, the init hook is too early for WordPress to know which page template you’re going to be using. (So the is_page_template() function will always return false).

Just go ahead and hook your function to wp_enqueue_scripts (which you’re probably already doing for your global CSS / JavaScript). And then check for the page template and run your logic inside that function.

Second, get_template_directory_uri() will return the web URL of your file and PHP’s file_exists expects a directory path on disk (not a URL). Use the get_template_directory() function to get that path, and enqueue it with get_template_directory_uri().

Here’s a working example, including the proper hook into wp_enqueue_scripts but you’ll want to move the contents of load_resources() into your own function in your theme that’s already hooked.

function load_resources() {
    if( is_page_template() ) {
        $page_template = basename( get_page_template(), '.php' );
        $css_file_path = get_template_directory() . '/css/pages/' . $page_template . '.css';
        $js_file_path = get_template_directory() . '/js/pages/' . $page_template . '.js';
        $css_file_uri = get_template_directory_uri() . '/css/pages/' . $page_template . '.css';
        $js_file_uri = get_template_directory_uri() . '/js/pages/' . $page_template . '.js';

        if(file_exists($css_file_path)){
            wp_enqueue_style($page_template, $css_file_uri);
        }

        if(file_exists($js_file_path)){
            wp_enqueue_script($page_template, $js_file_uri);
        }
    }
}
add_action( 'wp_enqueue_scripts', 'load_resources' );

Leave a Comment