Digging through https://github.com/WordPress/WordPress/blob/3.5.1/wp-includes/class.wp-dependencies.php all registered scripts are stored in the global $wp_scripts
.
You can access them directly through that, but I prefer to use the API when it exists. In this case, $wp_scripts->query()
returns a particular registered script (a _WP_Dependency
object - see source).
A _WP_Dependency
object stores the dependencies as an array of handles, which you can access directly, and insert a dependency. The following function does that:
/**
* Add $dep (script handle) to the array of dependencies for $handle
* @see http://wordpress.stackexchange.com/questions/100709/add-a-script-as-a-dependency-to-a-registered-script
* @param string $handle Script handle for which you want to add a dependency
* @param string $dep Script handle - the dependency you wish to add
*/
function wpse100709_append_dependency( $handle, $dep ){
global $wp_scripts;
$script = $wp_scripts->query( $handle, 'registered' );
if( !$script )
return false;
if( !in_array( $dep, $script->deps ) ){
$script->deps[] = $dep;
}
return true;
}
Obviously you must add this somewhere between the original script ($handle
) being registered and it being enqueued.
Example usage
Suppose script_a
has been registered on the init
hook with priority 10, and you want to add script_b
as a dependency:
add_action( 'init', 'wpse100709_register_script_b', 11 );
function wpse100709_register_script_b(){
//Register script b
wp_register_script( 'script_b', ... );
//Now add script b as being a pre-requisite for script a
wpse100709_append_dependency( 'script_a', 'script_b' )
//If script a is enqueued, script b is enqueued before it.
}
$wp_scripts
is the only thing that can be done here - but I wanted to if there were other/better ways.