Opened 16 months ago
#58873 new feature request
Add function to pass variables to scripts
Reported by: | apedog | Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | 5.7 |
Component: | Script Loader | Keywords: | |
Focuses: | Cc: |
Description
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
.