Created
April 22, 2011 13:23
-
-
Save dongilbert/936646 to your computer and use it in GitHub Desktop.
Helper function for registering and enqueueing CSS and JavaScript files within a WordPress plugin or theme.
This file contains 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
/** | |
* Helper function for registering and loading scripts and styles. | |
* Uses regex to determine if the file is CSS or JavaScript and calls | |
* the proper WordPress register and enqueue functions accordingly. | |
* | |
* @name ID to register with WordPress | |
* @file_path Path to actual file, relative to your plugin or theme, without preceding slash. | |
* @for Whether this is for a plugin or a theme. | |
*/ | |
function load_file($name, $file_path, $for = 'plugin') { | |
$file = trailingslashit(dirname(__FILE__)) . $file_path; | |
if($for == 'plugin') { | |
$url = plugins_url($file_path, dirname(__FILE__)); | |
} elseif($for == 'theme') { | |
$url = trailingslashit(dirname(get_bloginfo('stylesheet_url))) . $file_path; | |
} | |
if(preg_match('/\.js(\.gz)?/', $file_path)) { | |
$is_js = true; | |
} elseif(preg_match('/\.css(\.gz)?/', $file_path)) { | |
$is_css = true; | |
} else { | |
return false; | |
} | |
if(!file_exists($file)) { | |
return false; | |
} else { | |
if($is_js) { | |
wp_register_script($name, $url); | |
wp_enqueue_script($name); | |
} elseif($is_css) { | |
wp_register_style($name, $url); | |
wp_enqueue_style($name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment