Javascript in WordPress: 2 Functions 2 Save Your Day

Hey there! I'm currently working on a CLI tool to deploy WordPress apps to DigitalOcean. Check it out! It's free and open source.

I’ve introduced Javascript mode in the latest update of Quick Flickr Widget (1.2.7) for WordPress, and I just wanted to give you a short advice about handling javascript code in your WordPress plugins.

The wp_enqueue_script WordPress function helps you add javascript code to your head section, so you don’t have to mess up with the header.php file. One of the frequently asked questions is how do you get your plugin to load a javascript file that’s located in your plugin folder? Here’s the right way to do it:

$quick_flickr_plugin_url = trailingslashit(get_bloginfo('wpurl')).PLUGINDIR.'/'. dirname(plugin_basename(__FILE__));
wp_enqueue_script('quick_flickr_widget', $quick_flickr_plugin_url.'/quick_flickr_widget.js');

This should be in the init of your plugin (take a look at add_action).

Another good problem is passing your php variables to javascript. This is pretty simple with a WordPress function called wp_localize_script. Here’s a quick sample based on the flickr widget. Remember, we’re still in the init section.

wp_localize_script('quick_flickr_widget', 'FlickrOptions', $options);

You’ll get the $options variable output right before your javascript file in javascript format, like this:

<script type='text/javascript'>
/* <![CDATA[ */
	FlickrOptions = {
		title: "",
		view: "_m",
		before_flickr_widget: "<div class="flickr">",
		after_flickr_widget: "</div>",
// and so on

This makes it W3C valid (using CDATA) and easy to retrieve from within your javascript file: alert(FlickrOptions.title). There you go, one more reason to love WordPress ;)

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

1 comment