In: , , , , ,
On: 2008 / 04 / 11
Shorter URL for this post: http://ozh.in/hk

Adding javascript into an admin page is a critical part of plugin coding. Critical, because it is both trivial and probably reason #1 why it will conflict with other plugins if not done properly. When their plugin needs javascript, Good Plugin Coders™ have to make sure of the following points:

  • add javascript only once: if you need prototype.js, don't add it if it's already included
  • add javascript only on your plugin page: don't load yourscript.js in every admin page (with hook 'admin_head') including on other's plugin pages.

Doing so is hopefully very easy :

Add javascript only once

Need to include a javascript library or an external script? Don't ever use some straight echo '<script src="prototype.js"></script>';. The script might have been already loaded already, so there's no point in adding it again. Moreover, it can break everything: just add prototype after jQuery and you're ready for some trouble.

Instead, use wp_enqueue_script() :

  1. wp_enqueue_script('prototype');
  2. wp_enqueue_script('myscript', '/wp-content/plugins/myplugin/myscript.js');
  3. wp_enqueue_script('theirscript', 'http://theirsite.com/script.js');

Even simpler, if your script needs, say, Scriptaculous to work, just use:

  1. wp_enqueue_script('myscript', '/wp-content/plugins/myplugin/myscript.js', array('scriptaculous') );

Usage:
wp_enqueue_script( [string: handle], [optional string: src], [optional array: dependencies], [optional string: version number])

There are a number of predefined script handles: 'jquery', 'prototype', 'scriptaculous' and a bunch of others. Please refer to wp_enqueue_script() on the Codex for more details.

Add javascript only to your page

Never ever simply hook into 'admin_head' to add your script: not only you will be adding it to every admin pages (the Dashboard, Comments, etc…) but also to every other plugin pages. Seriously, half of the support question I've had with Who Sees Ads were because of WP-ContactForm adding its crappy javascript everywhere it could, including my plugin page.

Instead of testing current page URL in order to determine if it's your plugin page with a smart strpos() over $pagenow or $_SERVER['REQUEST_URI'], you should use hook 'admin_print_scripts-(page_hook)'

Example with a plugin that would create an admin page under "Manage":

  1. $mypage = add_management_page( 'myplugin', 'myplugin', 9, __FILE__, 'myplugin_admin_page' );
  2. add_action( "admin_print_scripts-$mypage", 'myplugin_admin_head' );
  3.  
  4. function myplugin_admin_head() {
  5.     // what your plugin needs in its <head>
  6. }

This snippet from Andrew Ozz on the wp-hackers mailing list.

Complete Example

This simple plugin will create an admin page under "Settings" in which a CSS and a JS file will be loaded. Check other pages of the admin area: they won't be affected.

Download load-js-example.

Summary

Be nice to other plugin coders. Add your javascript properly and only where needed. Thanks :)

Shorter URL

Want to share or tweet this post? Please use this short URL: http://ozh.in/hk

Metastuff

This entry "How To: Load Javascript With Your WordPress Plugin" was posted on 11/04/2008 at 10:35 am and is tagged with , , , , ,
Watch this discussion : Comments RSS 2.0.

61 Blablas

  1. Boyko Todorov says:

    Hey man,
    Thanks! Your post helped me!
    Take care!

  2. satya says:

    I've some problem with the plugin. Can someone have time to take a look at what am I doing wrong? :(

    I would appreciate all your help.

    Thanks
    Satya

  3. Martin says:

    Great post have been looking for this. I did run into an issue though using your exact word for word plugin I tried to load

    wp_enqueue_script( 'jquery-ui-core' );
    wp_enqueue_script( 'jquery-ui-accordion' );

    which I've been having a hell of a time loading in my plugin page and it still doesn't work. Any ideas why this might be I can't find a solution anywhere and yours seemed soooo right… almost :) Only if you have time, thanks either way I've started loading my custom scripts like you've posted.

  4. Brian Hogg says:

    @ Martin

    Have you tried doing something like this for your other scripts?

    1. wp_register_script( 'yourscript.js', plugins_url( 'static/js/yourscript.js', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), VERSION );
    2.     wp_enqueue_script( 'yourscript.js' );

    This ensures the scripts you've created that depend on jquery-ui-core and others get loaded in the proper order.

  5. Alex says:

    Hi,
    I was wondering if my method is good.
    I am using :
    add_options_page('Plugin settings', 'my plugin', 'manage_options', 'my-plugin', array(&$this,'adk_pro_setting') );

    so when i add the options page in the settings i also have the callback function which is adding all the css and js:
    wp_enqueue_script('itoggle',plugins_url('js/jquery.ibutton.min.js', __FILE__), array('jquery'));
    wp_register_style( 'fbc-style', plugins_url('css/backend.css', __FILE__) );
    wp_enqueue_style( 'fbc-style' );
    include 'settings.php';
    I checked out and it seems like i have the css and js only in my plugin pages.
    Any suggestions?
    Thank you

  6. Marco Avellaneda says:

    Muchas gracias por tus archivos para descargar, fueron los que me salvaron.
    Gracias

    Thankyou very much for the files in your plugin, they saved me.
    Thankyou

  7. al3ab says:

    Thank you for this nice post

  8. faysal shahi says:

    how to add JS to widget page?

  9. Björn says:

    Excellent post! Solved a lot of problems!

  10. Dante says:

    maybe don't use barcoded "/wp-content/plugins"

    Considering that the plugins directory can be moved, I think it would be best to use some of the build in functions to determine where your folders are

    See
    http://codex.wordpress.org/Determining_Plugin_and_Content_Directories

  11. Dima says:

    Thanks for the tip!
    But this is only for the admin page. And what to do with the front page? Are there some tricks for the front page?

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Gravatars: Curious about the little images next to each commenter's name ? Go to Gravatar and sign for a free account
Spam: Various spam plugins may be activated. I'll put pins in a Voodoo doll if you spam me.

Read more ?