As is often recommended, I used
wp_localize_script is quite simple with the following three steps.
- Enqueue your script that will use the variables using ‘wp_enqueue_script’
- Collect your parameters in an array
wp_localize_scriptto send the parameters to the script that will use them
For my plugin, I first enqueued the script that would be handling the creation of the Google Map and corresponding Markers.
I then gathered data from my posts and collected it in an array
$params the array is a multidimensional array that contains latitude, longitude, and description values for each post. Up to this point, everything was copacetic. I next tried to send the
$params array to the script using
wp_localize_script. This is where things broke down. Initially, I used the following code.
wp_localize_script creates a JSON encoded object that will appear in a
Instead of sending a JSON encoded object containing the values of the
wp_localize_script function, it will allow any value with the key
l10n_print_after to pass without modification. You must be careful when using this method as WordPress does not escape the data for you, so you need to be careful what you send to it. To remedy my situation, I used the following code to send the
Instead of printing the word “Array” as output, this code properly encoded my
By setting the second argument of the
wp_localize_script function to ‘markers’ and sending an array with the key
l10n_print_after as the third argument, two things happen. First, an empty object with the ‘markers’ is created.
Second, the value that was given the key
l10n_print_after is printed. In this case, I intentionally set the first part of this string to be ‘markers = ‘ so that I would assign the previously created ‘markers’ object to the JSON encoded object that was assigned the
l10n_print_after key in the
$params array. In the end, a useable object that contains the data needed for the markers is printed.