Easy question: I’m trying to understand wp_localize_script
.
Does wp_localize_script
call a JavaScript function or does it simply pass PHP parameters to JavaScript?
I want to pass PHP parameters to a JavaScript function and call the JS function.
wp_localize_script
takes an array of data (in PHP) spits out a javascript. It’s a way for you to add dynamic data for a specific script to the front end without having to hook into wp_head or wp_footer and echo it out yourself. More over,wp_localize_script
outputs your data right above the script you enqueued. Hooking intowp_head
orwp_footer
won’t do that.wp_localize_script
does not call javascript functions. It’s a way to do exactly what you want: pass dynamic data from the server side (PHP) to the client side (javascript).An Example
Your theme needs to take a piece of post meta data and make it accessible to a javascript function.
So you’d hook into
wp_enqueue_scripts
and do the following…Then somewhere the enqueued
script.js
file, you can get the post meta like this…Make sense?