How to load a javascript through your wordpress plugin

I’ve been struggling today to manage to make Backlinks to use the Scriptaculous script library in order to have the list of backlinks hidden until the viewer chooses to see them. While in the Division by Zer0 I already have those libraries loaded for my navigation, it’s certain that not everyone who is going to use it does the same.

Initially I was thinking of simply asking everyone to use a plugin loading these libraries as a dependency but that’s simply over the top for something this simple. Instead I decided to find out how to load the script within the plugin and to my delight I found out that not only does wordpress has functions explicitly for this purpose, but it already includes most common javascript libraries, inclusing Scriptaculous.

Unfortunately, although there were a number of guides trying to explain how to use this, none of them was complete. Simply adding enqueue_script in my function didn’t work and I couldn’t see a full example.

Fortunately someone had thought to add a mailing list discussion which gave me the solution after a few pages. I need to use the template_redirect hook (wp_head is not good, I tried) and I need to put that at the very start of my plugin, after the information but before any function begins. It then needs to call a function which enqueues the scriptaculous effects of which “blind” is used by Backlinks

The end result looks like this

add_action('template_redirect', 'addeffects');
function addeffects() {
if (function_exists('wp_enqueue_script')) wp_enqueue_script('scriptaculous-effects');
}

Of course, the name of the function can be anything you like and you can call any javascript library you wish instead of scriptaculous-effects. Feel free to download the whole plugin to see the whole code.


About this entry