Skip to content

Instantly share code, notes, and snippets.

@dongilbert
Created April 22, 2011 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongilbert/936646 to your computer and use it in GitHub Desktop.
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.
/**
* 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