Javascript in WordPress: 2 Functions 2 Save Your Day

May 4th, 2009

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.

Working with Javascript in WordPress

Working with Javascript in WordPress

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: "&lt;div class=&quot;flickr&quot;&gt;",
		after_flickr_widget: "&lt;/div&gt;",
// 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 ;)

Related posts:

  1. Quick Flickr Widget: Empowered by Thickbox
  2. Thickbox and jQuery in WordPress 2.8
  3. Javascript: Element Suicide
  4. Inspired: Javascript & jQuery Love
  5. WordPress Plugins: It’s Flickr Time!

Tagged: , , , ,
Shortlink: http://kovshenin.com/739

Permalink or share:
  • Twitter
  • Digg
  • Facebook
  • del.icio.us
  • FriendFeed
  • Technorati
  • Google Bookmarks
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • StumbleUpon
  • Print
  • email

One Response to “Javascript in WordPress: 2 Functions 2 Save Your Day”

Including pingbacks & trackbacks

Leave a Reply