[wp-trac] [WordPress Trac] #54958: Inconsistent behaviour for wp_add_inline_script between block-based and standard themes

WordPress Trac noreply at wordpress.org
Thu Jul 21 13:12:35 UTC 2022


#54958: Inconsistent behaviour for wp_add_inline_script between block-based and
standard themes
---------------------------+------------------------------
 Reporter:  Rustaurius     |       Owner:  (none)
     Type:  defect (bug)   |      Status:  reopened
 Priority:  normal         |   Milestone:  Awaiting Review
Component:  Script Loader  |     Version:
 Severity:  normal         |  Resolution:
 Keywords:                 |     Focuses:
---------------------------+------------------------------

Comment (by luigipulcini):

 We extensively analyzed the situation and it appears that block themes (or
 at least Twenty Twenty-Two) fire the `wp_enqueue_scripts` action only
 **after** the `the_post` action and, in turn, after `the_content`.

 So, while plugins registering a script during `wp_enqueue_scripts` will
 find it already registered when any shortcode callback is executed in
 regular themes, the same is not true for block themes. For them, a
 shortcode callback will be executed before `wp_enqueue_scripts`, thus
 before a plugin had a chance to register the script.

 In general, using `wp_localize_script` and `wp_add_inline_script` should
 always be done at the same time with the registration. Therefore, if you
 are registering the script inside `wp_enqueue_scripts` and, at the same
 time, adding the inline script you need, then you are free to enqueue the
 script during the shortcode callback by using `wp_enqueue_script` with the
 handle only. In fact, WordPress has a mechanism to automatically re-
 enqueue a script that was prematurely enqueued before the registration
 whenever the script gets finally registered. So, from that point of view,
 the change in block themes doesn't create any harm. But
 `wp_localize_script` and `wp_add_inline_script` **''must''** always be
 executed after the script is registered.

 In those situations where a block theme is used and the javascript
 parameters are based on values calculated inside the shortcode callback,
 there is no solution other than **''registering''** (not just
 **''enqueuing''**) the script and add the inline script **''inside''** the
 shortcode callback itself, even if that happens before
 `wp_enqueue_scripts`. Since WordPress cannot really register a script
 twice, this second approach is perfectly viable and effective.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/54958#comment:8>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list