How to load JavaScript in WordPress plugins

If you want to load some JavaScript files from your WordPress plugin you have at least two options.

Head hooks

When building up a page, just before the closing tag of the head element, a theme should call actions hooked on wp-head. Those actions only need to output what they want to include into the head element, like script files.

What if a theme does not do that? Well, I’d include it into the so called “known issues”. For example, my last WordPress plugin, won’t work in this case. I think it’s better not to find a workaround, so that theme authors understand that they must follow WordPress standards.

On the other hand, there is also an admin-head hook, which is the wp-head hook counterpart when building up admin pages. For example, you could use the following function.

<?php

function load_into_head() { 
	$ADMIN_VIEW = "alert( 'Hello Admin!' );";
	$USERS_VIEW = "alert( 'Hello World!' );";
	?>
<script type="text/javascript">
	<?php
		if( is_admin() ) { echo $ADMIN_VIEW; }
		else             { echo $USERS_VIEW; } 
	?>
</script>
	<?php 
}

add_action( is_admin() ? 'admin_head' : 'wp_head', 'load_into_head' );

?>

Script API

WordPress provides also a good Script API that will let you do anything you want with script files, following WordPress standards. These are the main functions:

  1. wp_deregister_script
  2. wp_register_script
  3. wp_enqueue_script
  4. wp_print_scripts (action hook)
  5. print_scripts_array (filter hook)

The general idea is that you write a function for loading your scripts using wp_deregister_script, wp_register_script, and wp_enqueue_script, and hook it on wp_print_scripts. If you also need to fine tune the order in which files are loaded or if they have to be loaded at all, then you can write another function and hook it on print_scripts_array.

deregister, register, and enqueue

wp_register_script let’s you create an alias and define dependencies for each script file. If a script file with the same alias was already registered, then your registration is ignored. This is a policy for conflict resolution (the first registration wins) that may help you, if you know it.

wp_deregister_script let’s you remove an alias. If the alias you give doesn’t exist, nothing happens. Tipically you use this function for forcing a new registration of an already registered alias: first you deregister and then register again.

wp_enqueue_script prepares the loading of a script. If the script was registered with some dependencies, this function automatically prepares their loading too, recursively, making sure each script will be loaded only once and before any script depending on it.

For example, jQuery 1.2.3 is registered by WordPress 2.5, but let’s say that you want to always download the latest version. You could use the following function.

<?php

function load_with_api() {
	wp_deregister_script( 'jquery' );
	wp_register_script( 'jquery', 'http://code.jquery.com/jquery-latest.pack.js', false, '' );

	//keep jQuery and Prototype compatible
	$url = get_bloginfo('wpurl').'/wp-content/plugins/my-plugin';
	wp_register_script( 'jquery_no_conflict', $url . '/jquery_no_conflict.js', array( 'jquery' ), '' );	
	wp_enqueue_script( 'jquery_no_conflict' );
}

add_action( 'wp_print_scripts', 'myOwnTheme_init' );

?>

Keeping jQuery and Prototype compatible is a needed functionality, because WordPress uses both and they both use $ as a global symbol. In fact, the jQuery file packed with WordPress includes the compatibility setting.

Fine tuning

If you want your scripts to be loaded in a particular order, with one script before or after another, maybe with respect to one that was registered by WordPress itself, or by other plugins, then you can write a function for the print_scripts_array filter.

For example, to load the jquery_no_conflict file just after the jquery file, you can use the following function.

<?php

function jquery_no_conflict_follows_jquery( $js_array ) {
	if ( false === $jquery = array_search( 'jquery', $js_array ) )
		return $js_array;

	if ( false === $jquery_no_conflict = array_search( 'jquery_no_conflict', $js_array ) )
		return $js_array;

	if ( $jquery_no_conflict == $jquery + 1 )
		return $js_array;

	array_splice( $js_array, $jquery + 1, 0, 'jquery_no_conflict' );

	unset($js_array[$jquery_no_conflict + ($jquery_no_conflict < $jquery ? 0 : 1)]);

	return $js_array;
}

add_filter( 'print_scripts_array', 'jquery_no_conflict_follows_jquery' );

?>

My Own Theme

If you want to see all this in action, you can install the My Own Theme plugin.

Tagged with:
Posted in Uncategorized
14 comments on “How to load JavaScript in WordPress plugins
  1. Great blog. I like layout!!!!

  2. Bob says:

    Does anyone know how to add javascript code rather than a javascript file?

  3. Bob says:

    Sorry, I mean instead of a .js file

  4. indy says:

    can somebody please tell me if there’s a way to check if a script has been registered?
    at a certain point in the php code i have to do – in pseudo code -
    if !registered(“mootools”) echo “<script src=’mootools.js’></script>”
    thanks for any help

  5. chinmoy says:

    I have the jquery js in my site but it does not load during the site load!!! Dont remember if I did any optimization.

  6. A brother ;) says:

    Thanks,I have searched a lot to manage loading “jquery”(conflict problem),I’ll try this. Second in second textarea function name “load_with_api()” must be “myOwnTheme_init()” ;)

  7. Blutarsky says:

    I am experiencing a little problem when using jQuery to inject contents in a Worpdress page.

    Basically I’m using an external php file, that holds the code to create content being injected. The external file is called topposts.php.

    If the file is included via php (using include, or require) it works perfectly, but when loaded using JQuery an error is issued, with a “call to undefined function”.

    It looks like jQuery load is executed in such a way it doesn’t “see” WordPress at all.

    Code:

    ‘In index.php
    .
    .
    .

    .
    .
    .
    .

    jQuery.noConflict();
    jQuery(“#foo”).load(“/wp-content/themes/tgv1/topposts.php”, “”,
    function(responseText, textStatus, XMLHttpRequest) {
    if(textStatus == ‘error’) {
    jQuery(‘#foo’).html(‘There was an error making the AJAX request’);
    }});

    then

    ‘in topposts.php

    Any idea?

  8. Osman Titiz says:

    Hello, I searched a lot but I couldn’t find any solution :( I have problems when I try to load jquery. I have been developing a widget and I need to load my own jquery because I use jquery.cycle.all.min.v.2.65.js and it needs to jQuery v1.2.6.
    The problems are
    - when I load the widget in wordpress-2.5, 2.6 my widget doesn’t work because jquery version is older (although written v1.2.6, it doesnt work)
    So, I must load my own jquery, It worked but now there is another problem which if theme or plugin has loaded jquery, my widget doesn’t work because of crash(reloading jquery)
    I used noconflict and also I tried to load jquery by doing but they didn’t solve my problem. Do you have any idea what should I do? Thanks.. :)

    1.
    wp_enqueue_script(‘iyikidogdun_jquery’, $src = ‘/wp-content/plugins/iyikidogdun/jquery_iyikidogdun.js’, $ver = ’1.3.2_iyikidogdun’ );
    wp_enqueue_script(‘jquery.cycle.iyikidogdun’,'/wp-content/plugins/iyikidogdun/jquery.cycle.all.min.v.2.65.js’,array(‘iyikidogdun_jquery’),$ver = ’2.65_iyikidogdun’);

    2.(loading before $before_widget but although has been loaded,my widget doesn’t work)

  9. Dizi izle says:

    can somebody please tell me if there’s a way to check if a script has been registered?
    at a certain point in the php code i have to do – in pseudo code -
    if !registered(”mootools”) echo “”
    thanks for any help

  10. Artem says:

    If I were to keep both functions inside a class, how would I apply the filter to the array if I would call it from my constructor?

    This doesnt work. Its saying its missing an argument, obviously.
    add_filter(‘print_scripts_array’, $this->jquery_no_conflict_follows_jquery());

  11. cam mozaik says:

    Thanks a lot! I am just learning Information.
    Php and this was very easy to follow and helped a lot.
    You really took time to explain every little bit.
    Thanks again…

  12. Really helpful article Andrea!Thanks a lot.

  13. Wonder full many things for sharing such a good stuff.

  14. Thong Tran says:

    Thank you for the post. It is not easy to add Javascript and CSS to WordPress and your post helps a lots.

3 Pings/Trackbacks for "How to load JavaScript in WordPress plugins"
  1. [...] ??? ?? ?? ???????? ? ??????????, ??? ?? ?????? ????????? ? ?????? How to load JavaScript in WordPress plugins [...]

  2. [...] In: WordPress plugins 18 Aug 2009 Go to Source [...]

  3. [...] Так же не забываем о конфликтах, как их обойти почитайте в статье How to load JavaScript in WordPress plugins [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>