I myself have just stumbled upon this issue.
As @sanzeeb3 pointed out, this works perfectly fine in traditional themes but stops working only in block themes. It turns out that wp_enqueue_scripts
fires later in block themes than it does in traditional ones. As a consequence, when you try to enqueue a script simply using its handle, the script is not found in the list of the registered scripts. And, in turn, wp_localize_script/wp_add_inline_script
fail to find the handle to attach their data to.
Still, this is perfectly achievable by using wp_localize_script/wp_add_inline_script
. The following code amends what @sanzeeb3 originally had and works in block themes as well as traditional ones, without resorting to a wp_footer
callback:
add_action( 'wp_enqueue_scripts', function() {
wp_register_script( 'my-script', 'https://example.com/script.js', array(), '0.0.1', false );
} );
add_shortcode( 'my_shortcode', function() {
if ( ! wp_script_is( 'my-script', 'registered' ) ) {
wp_register_script( 'my-script', 'https://example.com/script.js', array(), '0.0.1', false );
}
wp_enqueue_script( 'my-script' );
wp_localize_script(
'my-script',
'my_params',
array(
'is_okay' => 'Yes'
)
);
return 'Shortcode Content';
} );
Please note that it is enough to verify whether the script has already been registered. In case it hasn’t (because in block themes wp_enqueue_scripts
has not fired yet), the script can be registered at this time, inside the shortcode. A similar condition could be added to the wp_enqueue_scripts
callback but that would be redundant because wp_register_script()
invokes wp_scripts()->add()
which immediately bails out if the script has already been registered.
With that adjustment alone, the original code from @sanzeeb3 works just fine.
I hope this can help others.
PS: if you consider that is conceptually impossible for WordPress to register a script twice, the condition can even be removed and the script will be registered inside the shortcode: if it is already registered, wp_register_script()
will return prematurely anyway, so it is just a matter of preference and code style.