Chris Farrell Membership
Trellian
Cash Lady
This site uses cookies. By continuing to browse the site, you are agreeing to our use of cookies. Find out more.

161 Javascript Inclusion with Plugins

 Posted by  Add comments
 

161 Javascript Inclusion with Plugins

Part of the "How to Write a WordPress Plugin" Series

Objectives

In this lesson we will discuss and demonstrate the use of JavaScript with your WordPress plugin. This information is equally appropriate to theme design.

Almost all WordPress Themes and Plugins use or are reliant upon JavaScript and Cascading Style Sheets (CSS) these days. To make your plugins and themes easier to maintain, I recommend always placing the files associated with these items in separate folders.

As always there are many ways to accomplish a task and in this lesson we will show just a few methods specific to WordPress that will allow you to load scripts and avoid conflicts with other themes and plugins.

The use of these functions will also avoid problems that will arise when your themes or plugins both use the same JavaScript library or if Prototype and jQuery are both used on the same site.

Contents

 

—– Insert The Video —–

 

The Wp_Register_Script and Wp_Enqueue_Script Functions

The functions, wp_register_script and wp_enqueue_script, are used to add JavaScript to the html of a page, either in the header or the footer.

The Problem Defined

For a moment, just imagine you’ve been using a theme on your WordPress site without a problem. This theme uses jQuery to add AJAX functionality to your site.

Today, you decide to add a plugin to your WordPress site. This plugin also uses jQuery for the JavaScript.

You activate the plugin and instead of the super-fabulous result you were expecting you end up with a broken site. None of the JavaScript is working and your visitors are stuck on the home page.

After investigation, you see the following code in the HTML of your WordPress site:

<script type='text/JavaScript'
    src='/wp-content/themes/fabulous/jQuery-1.4.2.js'></script>
<script type='text/JavaScript'
    src='/wp-content/plugins/super/jQuery-1.3.2.js'></script>

The problem, both the theme and the plugin are attempting to load the jQuery library. To further complicates matters, each is requesting a different version.

The theme is expecting jQuery version 1.4.2 but the plugin is replacing it with jQuery version 1.3.2. So any functionality added to jQuery in version 1.4.2 is lost and an error occurs if this functionality is requested.

Fortunately the WordPress developers envisioned this problem and provided a solution, hence this tutorial.

Libraries Included with WordPress

WordPress comes with a number of JavaScript libraries pre-registered, so you need not include these libraries in your theme. All you need to do is include them as dependencies of your custom JavaScript and WordPress will do the work.

Some of the libraries included with WordPress are:

  • jQuery – with the handle ‘jQuery’, runs in no conflict mode
    WP 3.0 will include version 1.4.2 of jQuery
  • Scriptaculous – with the handle ‘scriptaculous’
  • SWF Object – with the handle ‘swfobject’
  • Prototype Framework – with the handle ‘prototype’

A full list of pre-registered script can be found in the codex, see the links at the end of this article.

Registering Your Scripts – Wp_Register_Script

The wp_register_script can be thought of as a safe way of registering JavaScript in WordPress (without adding it to the generated page) for later use with wp_enqueue_script.. Used by itself, it has no effect on your HTML whatsoever.

Usage

wp_register_script( 
    $handle, /* (string) (required) Name of the script. Should be unique as it is used as a handle for later use with wp_enqueue_script. /
    $src, /* (string) (optional) URL to the script. /
    $deps, /* (array) (optional) Array of handles of any script that this script depends on. /
    $ver, /* (string) (optional) String specifying the script version number. /
    $in_footer /* (boolean) (optional) If true the script is placed at the bottom of the <body>. */
);

Example wp_register_script

If your theme’s JavaScript can be loaded in the footer and relies on script.js’, you would register your script with the following code:

wp_register_script (
    'my_script_handle', /* handle */
    'http://yourdomain.com/wpcontent/plugins/your-plugin-directory/js/script.js', /* src */
    array('prototype'), /* deps */
    '1.0', /* ver */
    true /* in_footer */
);

Note: You should never hardcode URLs to local scripts, use Function Reference/plugins_url (for Plugins) and Function Reference/get_template_directory_uri (for Themes) to get a proper URL.

Enqueueing Your Scripts – Wp_Enqueue_Script

The wp_enqueue_script is a safe way of adding JavaScript to a WordPress generated page. The wp_enqueue_script function outputs your JavaScript to the HTML of the page, either as a result of the wp_head() or the wp_footer() call in your PHP.

The wp_enqueue_script function does the same thing as wp_register_script. If $src is provided, the enqueue function automatically registers the script for you, thus making the wp_register_script function somewhat unnecessary. However, the wp_register_script does allow you to register your scripts manually so you can load all of your JavaScript’s using one wp_enqueue_script function.

Usage

wp_enqueue_script( 
    $handle, //(string) (required) Name of the script. Lowercase string.
    $src, // (string) (optional) URL to the script.
    $deps, // (array) (optional) Array of handles of any script that this script depends on
    $ver, // (string) (optional) String specifying the script version number
    $in_footer // (boolean) (optional) If true the script is placed at the bottom of the <body>.
);

Note: These functions only work as expected if both wp_head() and wp_footer() are included in header.php and footer.php respectively.

Example wp_enqueue_script

If you have pre-registered your script using the wp_register_script (as above), the code is:

if (!is_admin()) {
    wp_enqueue_script('my_script_handle'); //(string) (required) Name of the script.
}

Do check that your visitor is outside of the admin area, !is_admin() as these functions can be used to add JavaScript to both the visitor and admin areas. More often than not, you’ll want to leave the admin area alone.

If we were to call the same custom script as we did in the wp_register_script example, it would be called in exactly the same way, like this:

wp_enqueue_script(
    'my_script_handle', /* handle */
    'http://yourdomain.com/wpcontent/plugins/your-plugin-directory/js/script.js', /* src */
    array('prototype'), /* deps */
    '1.0', /* ver */
    true /* in_footer */
);

In a more realistic example you would start by hooking your function into WordPress.

add_action('wp_enqueue_scripts', 'pk_add_scripts');

By using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate scripts, which will cause post editing (amongst other things) to break after upgrades.

Next, add the scripts you want to use:

function pk_add_scripts ()
{
    if (!is_admin()) {
        $path_to_your_files = plugins_url( 'js/my-script.js', __FILE__ );
        /* Load the WP scriptaculous script */
        wp_enqueue_script('scriptaculous');
 
        /* Use the CDN copy of jQuery instead of WordPress’s */
        wp_deregister_script( 'jquery' );
        wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jQuery/1.6/jQuery.min.js');
        wp_enqueue_script( 'jquery' );
 
        /* Enter your own custom script */
        wp_enqueue_script('your_custom_file', $path_to_your_files . "/js/your_custom_file.js", array('jquery'), '1.2', true );
    }
}

Aside: JQuery Noconflict Wrappers

The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. jQuery’s standard mode includes the $ variable as an alias. In "no-confict" mode, the $ shortcut is not available and the longer jQuery format is used.

WordPress Example:

$(document).ready(function(){
    $(#somefunction)
});

Becomes:

jQuery(document).ready(function(){
    jQuery(#somefunction)
});

In order to use the default jQuery shortcut of $, you can use the following wrapper around your code which will be executed when the page finishes loading.

jQuery(document).ready(function($) {
    // $() will work as an alias for jQuery() inside of this function
});

If you want your code to execute immediately then you can use this wrapper method instead:

(function($) {
    // $() will work as an alias for jQuery() inside of this function
})(jQuery);

Conclusion – Summary

Using this way to add JavaScript to your code is recommended for all plugins. Not only it is elegant and efficient but it is usually faster than manually printing your scripts and parameters.

Well, that’s all for this tutorial on How to Write a WordPress Plugin, see you in the next lesson.

Links Used in this Lesson

http://codex.WordPress.org/Function_Reference/wp_register_script
http://codex.WordPress.org/Function_Reference/wp_enqueue_script
http://codex.WordPress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress
http://codex.WordPress.org/Function_Reference/plugins_url
http://codex.WordPress.org/Function_Reference/get_template_directory_uri


KingSolutions.org.uk is hosted on JustHost

 Leave a Reply

(required)

(required)

90 queries in 1.053 seconds (Child).