Wordpress Script Handling

Wordpress has some great stuff for handling scripts. You can use wp_enqueue_script() or wp_register_script() to handle scripts. Since there are some scripts that I use so regularly, I decided to automate the process a little more. Basically, I create a js directory inside my template directory, and place the JavaScript files I plan to use there. Each can have certain keywords in the comments at the top of the file to set it’s handle, version, dependencies, as well as whether to enqueue it automatically. The comments may look something like:

/*
Handle: xavisys
Version: 0.1
Deps: scriptaculous-effects
Enqueue: true
*/

/*
Version: 1.5.4.1
Handle: validation
Deps: scriptaculous-effects
*/

/*
Handle: x_contact
Version: 0.1
Deps: validation
*/

Basically, if enqueue is set to true, it will automatically load the file. Otherwise, it will just register it, so that you can use the handle to enqueue it when needed. All you need to do is add the following code to your functions.php file:

<?php
class handleScripts {
	private static $scripts_to_enqueue = array();
	public static function enqueue_scripts() {
		foreach (self::$scripts_to_enqueue as $handle) {
			wp_enqueue_script($handle);
		}
	}

	public static function register_scripts() {
		$x_js_files = scandir(TEMPLATEPATH.'/js');
		foreach ($x_js_files as $x_js_file) {
			if (strtolower(substr($x_js_file, -3)) == '.js') {
				$x_f_data = file_get_contents(TEMPLATEPATH."/js/{$x_js_file}");
				preg_match( "|Handle:(.*)|i", $x_f_data, $x_js_handle );
				preg_match( "|Version:(.*)|i", $x_f_data, $x_js_version );
				preg_match( "|Deps:(.*)|i", $x_f_data, $x_js_deps );
				preg_match( "|Enqueue:(.*)|i", $x_f_data, $x_js_enqueue );

				$x_js_handle = (isset($x_js_handle[1]))? trim($x_js_handle[1]):basename(strtolower($x_js_file), '.js');
				$x_js_version = (isset($x_js_version[1]))? trim($x_js_version[1]):'1';
				$x_js_deps = (isset($x_js_deps[1]))? preg_split('/\s*,\s*/', trim($x_js_deps[1])) : array();
				$x_js_enqueue = (isset($x_js_enqueue[1]) && strtolower(trim($x_js_enqueue[1])) == 'true');

				wp_register_script($x_js_handle, get_bloginfo('template_directory')."/js/{$x_js_file}", $x_js_deps, $x_js_version);
				if ($x_js_enqueue) {
					self::$scripts_to_enqueue[] = $x_js_handle;
				}
			}
		}
	}
}

add_action('init', array('handleScripts','register_scripts'));
add_action('wp_head', array('handleScripts','enqueue_scripts'));

Related Posts:

About AaronCampbell
Aaron is the man behind the curtain here at Xavisys. He gets things done and really knows his way around the code.

Comments

One Response to “Wordpress Script Handling”
  1. Y920 says:

    Always Explanation is useful..

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!