Opened 3 years ago
Last modified 3 years ago
#54777 new defect (bug)
passing empty object to wp_localize_script will convert it to empty array instead of empty object
Reported by: | erikdemarco | Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | Script Loader | Keywords: | |
Focuses: | Cc: |
Description
This will correctly converted to js object:
wp_localize_script( $handle, $object_name, array( "foo" => "Foo value", "bar" => "Bar value" ) );
the value will be:
{"foo":"Foo value","bar":"Bar value"}
But passing empty array will be converted to js empty array:
wp_localize_script( $handle, $object_name, array() );
the value will be:
[]
We want to pass empty array because we want to prepare the global js variable to be used later. But because of the inconsistency it can cause problem if we want to loop it for later use. since we use different method to loop object and array in javascript.
Note: See
TracTickets for help on using
tickets.
Related: #25280
The recommend approach is to use
wp_add_inline_script()
for this use case.