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

WordPress Trac noreply at wordpress.org
Thu Aug 14 23:45:18 UTC 2025


#58873: Add function to pass variables to scripts
-----------------------------+-------------------------
 Reporter:  apedog           |       Owner:  (none)
     Type:  feature request  |      Status:  closed
 Priority:  normal           |   Milestone:
Component:  Script Loader    |     Version:  5.7
 Severity:  normal           |  Resolution:  worksforme
 Keywords:                   |     Focuses:
-----------------------------+-------------------------

Comment (by westonruter):

 @jonsurrell There is a downside to using `wp_localize_script()` in that it
 casts all top-level array items to strings, because this function is
 intended for i18n data. See #25280. Really, the better way to pass
 arbitrary data from PHP to a classic script is to use
 `wp_add_inline_script()`, although the DX is slightly less ergonomic.

 {{{#!php
 <?php
 wp_localize_script( $handle, 'foo', $data );
 }}}

 vs

 {{{#!php
 <?php
 wp_add_inline_script(
     $handle,
     sprintf( 'var foo = %s;', wp_json_encode( $data ) ),
     'before'
 );
 }}}

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


More information about the wp-trac mailing list