WordPress : Using Javascript libraries with your plugin or theme

When you develop a WordPress plugin or theme, you might want to make use of some of the Javascript libraries distributed with the WordPress package such as Prototype, Scriptaculous and jQuery.

Simple enough, they are in the “wp-includes/js/” folder, so what more is there to it? Can’t I just add a SCRIPT tag in the HEAD section (or any other part of the WordPress page for that matter)? Of course you can do that, but you’ll most likely be causing a headache for other plugin and theme developers out there since you’re not following WordPress conventions as you should when you simply dump a SCRIPT tag into the content of the page.

This is the mistake that most plugin developers make. They usually make use of the “wp_head” action hook and inject SCRIPT tags referencing these declared Javascript libraries into the HEAD section of the WordPress pages. Problem is that when you do this, and another plugin has already referenced any of these libraries, you are redeclaring them which results in a Javascript error on the page, terminating execution of any other Javascript on the page (both internally and externally).

So what is the correct way to do this? WordPress provides us (developers) with a function called wp_enqueue_script which allows you to safely reference the provided Javascript libraries and frameworks.

The first parameter of this function is the handle/name of the script. For example, if you wanted to reference the Prototype library, you would do something like below.

<?php wp_enqueue_script('prototype'); ?>

…where “prototype” could be replaced with any of the handles in the list below.

  • scriptaculous-root
    The Scriptaculous root without any of its sub-framework dependencies
     
  • jquery
    The jQuery library
     
  • thickbox
    Thickbox library, allowing you to display images, iframes, etc… in an overlay.
     
  • tiny_mce
    The tinyMce script which creates and powers the WYSIWYG HTML editor provided with WordPress 

…and a few more. For a full list of all the scripts distributed with WordPress, together with the handle for each script, visit the wp_enqueue_script documentation at the WordPress.org codex wiki.

Of course, you can add your own scripts as well, whether they are scripts you wrote yourself or other scripts distributed publicly, but not included with WordPress. When you add your own scripts, please ensure that you specify the second parameter (explained below) of the wp_enqueue_script function so that WordPress will know what the location of the script is.

The second parameter of the wp_enqueue_script function allows you to specify the source of the script, meaning the location of the script file, relevant to the root of your WordPress installation. For example, lets say that I placed a script with the filename “myscript.js” into the folder of a plugin I’m coding, where the folder name is “myplugin”, the value for the second parameter of the wp_enqueue_script function will be “/wp-content/plugins/myplugin/myscript.js”. See the example below.

<?php wp_enqueue_script('myscript', '/wp-content/plugins/myplugin/myscript.js'); ?>

The third parameter of the wp_enqueue_script function should always be an array (when specified). It tells WordPress which other scripts this script being enqueued depends on so that those scripts can be loaded before this one is loaded. For example, a custom script I wrote which I’m enqueueing is dependent on the Prototype library and the Scriptaculous framework. Therefore, I will specify them as dependencies. See the example below.

<?php wp_enqueue_script('myscript', '/wp-content/plugins/myplugin/myscript.js', array('prototype', 'scriptaculous')); ?>

The last parameter of the wp_enqueue_script function specifies the version number of the script being enqueued. This helps WordPress to always load the newest/latest script in case there are multiple, similar scripts which are different versions. See the example below.

<?php wp_enqueue_script('myscript', '/wp-content/plugins/myplugin/myscript.js', array('scriptaculous'), '1.0'); ?>

That’s all there is to it! No SCRIPT tags, no fuss!!! Please be considerate to other developers (and their plugins/themes) and use WordPress conventions as they were intended to be used.

  • Pingback: Surf Raporu 22 Haziran 2008 | Taylan Aktepe

  • Pingback: Wordpress : Using jQuery library with your plugin or theme

  • abubin

    I want to call jquery and another own java script but where do I put the wp_enqueue_script? I read all the howto and guide about wp_enqueue_script but non of them tells where to put the script. Aren’t these guides supposed to be read by people who doesn’t already know what to do with them?

    So, where do I put the scripts? in the loop? in some header file? in some function file? directly into my blog? where? in the moon?

  • http://tribulant.com lost-in-code

    @abubin

    Hi there,

    It depends on what you are doing.

    If you are developing a theme, you could put it in the header.php file, anywhere before the wp_head function is executed.

    If you’re going to do this with a plugin, you could add an action hook to the wp_head action or alternatively just put it in your plugin file so that the wp_enqueue_script function is fired when your plugin is loaded.

    I hope that helps.

    Best,
    Antonie

  • http://graemepirie.com Graeme

    I’ve created a “Garage Door Menu” using jquery and would like to insert it into the top of my wordpress blog, between the header and blog postings but I receive the following error:

    Warning: Division by zero in (folder structure/header.php)

  • http://www.jepson.no Magnus Jepson

    Hey thanks for this post and the post in the WooThemes forum. I was not aware of this function and it might save us a few support headaches in the future, which is always nice :)

  • http://tribulant.com Antonie Potgieter

    @Magnus
    Its a pleasure. I’m glad you found it useful.

  • Pingback: links for 2008-11-14 | Yostivanich.com

  • Pingback: Geek Week - This week jQuery tutorials, CSS3, & WordPress - PHP, XHTML, Web Design, Flash | JasonCypret.com

  • http://garimpando.net Renato

    Thanks for that! The most valuable part was the answer to abubin’s question!

  • http://geekyweekly.com Andrew

    I wish more plugin and theme developers were aware of this. It should really be the only way to include JavaScript on a WordPress page. Almost all of my plugin support goes towards telling people they have a plugin that is screwing up the Scriptaculous includes.

  • Miles

    I’m looking to create a mootools powered navigation in my theme. Would this function also cover mootools?

    If so, what would it look like?

  • http://tribulant.com Antonie Potgieter

    @Miles

    Thank you for your comment. Yes, you can use MooTools with wp_enqueue_script as well.

    Since MooTools isn’t integrated into WordPress, you’ll need to download the MooTools library, put it into your plugin or theme folder and reference it will wp_enqueue_script.

    To enqueue it, you’ll need to do something like this :

    < ?php wp_enqeueue_script('mootools', '/wp-content/themes/my-theme/mootools.js', false, '1.2.1'); ?>

    That should do it. Just change the second parameter to the correct dirname and basename of where you uploaded the Mootools library.

    To ensure that it is being loaded properly, simply check your site’s source code and check whether it has been injected into the HEAD section where the wp_head template function is executed.

    All the best,
    Antonie

  • http://virtualme.110mb.com virtual millenium

    Thank you for this information, I’m interested in plugins using mootools.

  • http://colorlabsproject.com michaeljubel

    thanks for the information, antoine. this will surely help us! thanks!

  • Pingback: WordPress : Enqueue Styles

  • http://sfunique.com Lex

    Arrgh! Thanks so much for the ‘bestpractice’ tips..however, after reading through all the comments and problems other people had, I still can’t solve mine. You see, even though jquery script is being included with ‘properly’ it does not work. There a ?ver=1.2.6 attached to the generated URL, but I don’t want this..could that be the problem? In fact, every script I include this way gets tagged a ?ver=… with no need. I’ve tried setting false for the ver parameter, but remains.

    Thanks for you time and help :)

    Cheers!

  • http://www.pornlewd.com porn lewd

    thanks!great tips

  • http://www.dineshchopra.com Accounting Homework

    Hi.
    I have a look like your working style.You are succesfully working man.

    Thanks.

  • http://www.sbox.ws Shoutbox

    Wow.. this is a really cool tip. I didn’t know wordpress allowed us to add custom made scripts.

  • http://link Matthew Maciak

    uSQQMx Hi can someone please translate for me thanx,

  • http://www.hikaye.biz hikaye

    Thank you for this information, I’m interested in plugins using mootools.

  • http://www.motion-effect.no Johnny

    Thanks for a really good explanation here about how this works, even for me thats not a programmer, but only understands the structure of the code :)

  • http://www.motion-effect.no Johnny

    Ok, the reason why I came to this post was becaouse I have a problem, again, Tribulant mailinglist plugin. The first time I bought it, it coused nothing but problems to my WordPress sites. Usually buggy, or conflicting with other plugins. I just renew to the latest version, v.3.7. But again, it still produces problems! I’m about to loose hope here.

    When I activate this plugin, in kills the function of another plugin on the site. A frontage slideshow (Featuared Content Gallery v.3.2.0) included with Woo Themes. It’s even totally slowing down my WP admin.

    So, what can one do to eliminate this problems with plugins conflicting. How can I fx control when to load plugin script in the header, like only on a certain page. Do I need to create a wp template for that page, loading another header.php`?

    I need to understand this now, because it has been a problem for me many times, and it slows down my work every time.

    Antonie, can you help me with this.

    Thanks people!

  • http://downcomforterset.info/ Down Comforter Sets

    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 a plugin.

  • http://mywebmastertips.com MyWebmasterTips

    I’m new to using WordPress with jQuery.

    Is once you add the .js file using the wp_enqueue_script function, do you have to do anything to the javascript code to make it work in WordPress?

    I’m having trouble with a script and was just wondering.

  • adrian

    I am desperately trying to this to work, and for the life of cannot figure out. I am using the p2 theme and maybe this is why. Here is what i am doing. In the header file (in between the head tags) i put this code:

    (the jquery in located in a js folder)

    Then, I pute this code into the sidebar php page :

    $(document).ready(function()
    {
    $(‘#Button1′).click(function() {
    location.reload();
    });
    });

    and nothing happens. Can someone please help???
    thanks,
    adrian

  • Pingback: WordPress: мої нотатки | Блоґ Виспянського Ігоря

  • http://www.duacara.com bisnis internet

    thanks for sharing on your tips nice guys

  • Pingback: » Using Javascript in Wordpress Themes

  • Ug

    Nice article.

    But for those of you who still can’t get this to work in your theme template files (just like me), when you are done en-queuing the script files inside of your ‘functions.php’ file, go back to your the ” (wherever it is) section of your template file and include the ‘wp_print_scripts’ function inside of a PHP code section. If other un-required scripts are being added, then use this instead ‘wp_print_scripts($handle)’ for each of the scripts you want to enqueue, with the ‘$handle’ argument being a string specifying the ‘handle’ you used for the ‘wp_enqueue_script’ function in your functions.php file.

    Hope this helps someone.

  • Ug

    Sorry, the comment parser removed some words in my comment. Thse sentence should be: “go back to your &lthead&gt section …

  • http://www.premiumwpthemess.com Wordpress

    Can you write article about using jquery items (slider,high-light) with wordpress themes ?

    Best Regards

  • http://www.rcaieftina.ro rca ieftin

    Is possible to inject the code in other zones of the WordPress code. I am interested in using in the sidebar of the Javascript. Is this possible ? And the site will remain stable after injection ? No security problem after that ?

  • http://gyanendragiri.in Gyanendra

    Nice article ! really helpful for avoid JavaScript conflict.