wp_register_script()
(see codex) allows you to specify dependencies: scripts that must be loaded before the one being registered is loaded (if it is loaded).
But suppose the script is a third-party one (WordPress or another plug-in) so that you are not the one calling wp_register_script()
. How can you inject a script as a dependency for a pre-registered script?
Remarks: In my particular use-case the dependency is not strict – the registered script does not require this second script, but the latter alters the original script.
A similar question could be asked for styles, but I suspect the answers would be nearly identical.
2 s
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.
}