This function adds data to scripts/styles that have been enqueued during the WordPress load.
Not really. It adds data to scripts/styles that’ve been registered
.
The data key that is set by
wp_localize_script
is ultimately overwritten by the call to$wp_scripts->add_data
, whereas if you callwp_localize_script
twice for the same script, the string will be properly concatenated.
Right. They both call the underlying (non-accessible, internal) API, so it gets overwritten (as you stated). This happens when it calls $this->get_data( $handle, 'data' );
.
Question
My main question is: should developers be using this function?
Answer
Simply said: Yes, when you got no other chance to do what you need.
Another example: Check if a script was registered (for e.g. json2/jquery
) and move it to the footer (check extra['group']
).
// Move scripts to the footer - in case it isn't already there
if ( ! $wp_scripts->get_data( 'json2', 'group' ) )
$wp_scripts->add_data( 'json2', 'group', 1 );
if ( ! $wp_scripts->get_data( 'jquery', 'group' ) )
$wp_scripts->add_data( 'jquery', 'group', 1 );
Note: This ↑ only works for data filed under extra
!
Additional notes
Counter-Question: Have you ever tried to add dependencies to scripts registered by core? For e.g.: Try to add JSON2
as needed deps to jQuery
. This isn’t possible without intercepting the global $wp_scripts
:
global $wp_scripts;
$scripts = array(
'jquery' => array( 'json2' )
,'jquery-form' => array( 'json2' )
);
foreach ( $scripts as $handle => $deps )
{
// Ugly hack: Intercept the global to force the "natural"/needed order: JSON2 » jQuery
$deps_default =& $wp_scripts->registered[ $handle ]->deps;
$wp_scripts->registered[ $handle ]->deps = array_merge( $deps_default, $deps );
}
There’s a whole load of things the class can’t do. So using something like ->add_data()
is imo fully valid. Just use what you got, as it’s still better then living the lacks of core classes.