I am attempting to dynamically load stylesheets and scripts based on the template name. So if I have a template named page-signup.php
then it will load the corresponding stylesheet page-signup.css
and page-signup.js
if they exist for that page from a specific directory in my theme folder.
Here is what I have so far in functions.php of my theme. It does not currently load any styles or scripts when the css and js files are present in the proper directory:
/**
* Auto loads scripts and styles based on the page name if they exist.
*/
function mytheme_bootstrap_page_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', 'mytheme_bootstrap_page_resources');
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' );