pass object/JSON to wp_localize_script

Indeed, wp_localize_script() is simple, it just adds quotes around the values and escapes the content, expecting all of them to be strings.

However, there is the l10n_print_after key of the array, which will be printed without any interference at all. It can be used to execute arbitrary code after the strings are passed. You can use it to pass your extra data.

$data = array(
    'layout_config' => {
      'ls' : {'sb1': 1}
    }
);
$reshuffled_data = array(
    'l10n_print_after' => 'my_localized_data=" . json_encode( $data ) . ";'
);
wp_localize_script('my-script-handle', 'my_localized_data', $reshuffled_data);

You will end up with code like this:

var my_localized_data = {}; // What is left of your array
my_localized_data = {'layout_config': {'ls': {'sb1': 1}}}; // From l10n_print_after

Leave a Comment