[wp-trac] [WordPress Trac] #58873: Add function to pass variables to scripts

WordPress Trac noreply at wordpress.org
Sat Jul 22 03:36:51 UTC 2023


#58873: Add function to pass variables to scripts
-----------------------------+-----------------------------
 Reporter:  apedog           |      Owner:  (none)
     Type:  feature request  |     Status:  new
 Priority:  normal           |  Milestone:  Awaiting Review
Component:  Script Loader    |    Version:  5.7
 Severity:  normal           |   Keywords:
  Focuses:                   |
-----------------------------+-----------------------------
 Since WordPress 5.7 using `wp_localize_scripts` to pass variables to
 registered scripts throws a `_doing_it_wrong` notice.

 The suggested "correct" way of passing variables to scripts, using
 `wp_add_inline_script`, feels like a step backwards.
 - Instead of just passing a variable name and value through a PHP
 function, that abstracts all of this away, we now have to write fully
 qualified JavaScript code in PHP strings.
 - We have to actually parse/decode the values being passed on a case-by-
 case basis. `wp_localize_script` did this reliably.
 - Using `wp_add_inline_script` is more verbose and prone to errors. Static
 analysis tools will not work on PHP strings.
 - It makes for uglier code that is less human-readable.

 On a personal note,
 Converting to `wp_add_inline_script` feels a lot more like I'm "doing it
 wrong" than using `wp_localize_script`. It's simple, short and it works.
 (I do feel chagrined to see Query Monitor show up brown on every page
 load. But not enough to go and make my code uglier.)
 I also doubt other "in the wild" developers will forego the use of
 `wp_localize_script` because of the `_doing_it_wrong` notice. The
 `wp_add_inline_script` alternative is simply not as robust.

 Suggestion:
 Add a function `wp_pass_variables_to_script` (or probably a shorter name)
 to re-introduce the robust functionality provided by `wp_localize_script`.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/58873>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list