Integrating jQuery plugins in WordPress

One of the most frequently asked questions on forums, blogs and mailing lists concerns the integration of jQuery plugins with WordPress. Integrating jQuery plugins with WordPress is not a matter of queuing scripts only, but it also means understanding the correct hierarchy and order by which scripts are executed within WordPress. Let's see the details of this topic.

Order and hierarchy

In WordPress, a jQuery plugin depends on the jQuery library itself. For that reason, you should always specify such a dependence when you register your plugins:

wp_enqueue_script('jquery');
wp_register_script('plugin', 'url/to/plugin.js', array('jquery'), '1.0', false);
wp_enqueue_script('plugin');

The wp_register_script() function takes as its third parameter an array containing all the scripts our plugin depends on. In this case, the main dependence script is jQuery.

If you don't follow this approach, your plugin is likely to fail.

Invoking the plugin

You should invoke your plugin just after the main plugin file, always respecting the hierarchy mentioned above. For that reason, your code should be put within a separate JavaScript file.

Within this file, you should always wrap your code in the main jQuery namespace, like so:

(function($) {

 $(function() {
 
  $(element).plugin();
 
 
 });


})(jQuery);

In the same way, your JavaScript file should be enqueued just after the main jQuery plugin:

wp_enqueue_script('jquery');
wp_register_script('plugin', 'url/to/plugin.js', array('jquery'), '1.0', false);
wp_enqueue_script('plugin');
wp_register_script('script', 'url/to/script.js', array('jquery'), '1.0', false);
wp_enqueue_script('script');

As you can see, we're always respecting the script hierarchy established by WordPress.

Leave a Reply

Note: Only a member of this blog may post a comment.