I have a plugin that, among other things, has a javascript file that requires a few user specific settings. What would be the best way to get those settings into javascript from the plugin’s settings parameters?
In other words, if I make those settings part of the settings page where the user can enter them, how would I best be able to get those values into javascript? Would I have to use something to append some script tags and set them via PHP on every page load? Would setting a cookie be a better way to do this?
better is, you use the functions of WP for this, a example for multilanguage:
use this in js-file:
} );
Also see the post from Otto
There are a couple of ways that you could do this, one of which I’ve done before, the other I haven’t, but I have used for XML configuration files.
The first one is to include the variables in a script tag inside the WP header or footer, before the script tag where you include your JS file, for example:
The other alternative would be to include the JS inside of a PHP file which is included inside of a script tag.
Inside this file you would include your javascript, and as PHP would parse it you would be able to include PHP calls in a similar fashion to above, simply echoing out the data/options which you require. One thing to note is that you might need to set the headers for the output as
text/javascript
.Personally I much prefer the first method, and is what I use when I have user changeable settings which affect javascript files.