Skip to content

Instantly share code, notes, and snippets.

@adamfisher
Created August 2, 2014 20:23
Show Gist options
  • Save adamfisher/a6f9abec8449575e8bd1 to your computer and use it in GitHub Desktop.
Save adamfisher/a6f9abec8449575e8bd1 to your computer and use it in GitHub Desktop.
Auto Load WordPress CSS & JS Dynamically for Pages
/**
* 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_stylesheet_directory() . "/css/templates/$page_template.css";
$js_file_path = get_stylesheet_directory() . "/js/templates/$page_template.js";
$css_file_uri = get_stylesheet_directory_uri() . "/css/templates/$page_template.css";
$js_file_uri = get_stylesheet_directory_uri() . "/js/templates/$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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment