Last active
January 9, 2017 14:10
-
-
Save corenominal/97791f171482c391b7e307f87e8d5648 to your computer and use it in GitHub Desktop.
Conditionally include additional CSS and JS for page templates in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( ! defined( 'WPINC' ) ) { die('Direct access prohibited!'); } | |
/** | |
* Conditionally include additional CSS and JS for page templates | |
*/ | |
function conditionally_enqueue_scripts() | |
{ | |
// Test for page template | |
if( is_page_template() ) | |
{ | |
// Get template name and assign | |
$name = rtrim( basename( get_page_template() ), '.php' ); | |
// Test for existence of CSS file with same name | |
if( file_exists( get_template_directory() . '/css/' . $name . '.css' ) ) | |
{ | |
// Enqueue the CSS | |
// For options, see: https://developer.wordpress.org/reference/functions/wp_enqueue_style/ | |
wp_enqueue_style( $name . '_css', get_template_directory_uri() . '/css/' . $name . '.css', false ); | |
} | |
// Test for existence of JS file with same name | |
if( file_exists( get_template_directory() . '/js/' . $name . '.js' ) ) | |
{ | |
// Enqueue the JS | |
// For options, see: https://developer.wordpress.org/reference/functions/wp_enqueue_script/ | |
wp_enqueue_script( $name . '_js', get_template_directory_uri() . '/js/' . $name . '.js', array(), false, true ); | |
} | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'conditionally_enqueue_scripts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment