Best practice for adding JavaScript code to WordPress plugins

This article is intended as a guide on how to add JavaScript code to your plugins.

Here is a practical example from WP Wall plugin.

Start by hooking your function to wp_print_action:

add_action('wp_print_scripts', 'WPWall_ScriptsAction');

Next, add the scripts you want to use:

function WPWall_ScriptsAction()
{
 $wp_wall_plugin_url = trailingslashit( get_bloginfo('wpurl') ).PLUGINDIR.'/'. dirname( plugin_basename(__FILE__) );
 
 if (!is_admin())
	{
	  wp_enqueue_script('jquery');
	  wp_enqueue_script('jquery-form');
	  wp_enqueue_script('wp_wall_script', $wp_wall_plugin_url.'/wp-wall.js', array('jquery', 'jquery-form'));
	  wp_localize_script( 'wp_wall_script', 'WPWallSettings', array(
	  	'refreshtime' => 5,
                'mode' => "auto"
		));
	}
}

The code above checks if the opened page is not an admin page as we do not want to load scripts there. Next we use wp_enqueue_script function which can add predefined scripts (like jquery, thickbox, sack etc.) or your own scripts to the printing 'queue'. This will ensure that all scripts will be loaded only once even if referenced multiple times by different plugins

Passing parameters to JavaScript using wp_localize_script

WordPress provides an elegant way to pass parameters to your JavaScript code using wp_localize_script function.

WordPress will automatically add the parameters before the call to your script, even using CDATA for validation.

In the previous example refreshtime and mode parameters were passed and can be easily accessed in JavaScript:

refresh = parseInt( WPWallSettings.refreshtime );
 
mode = WPWallSettings.mode;

Load scripts only when needed

In the example we had a simple check to make sure the scripts are not loaded on admin pages.

In admin pages you can specify exactly on what pages you want the scripts to load.

add_action( "admin_print_scripts-options.php", 'my_admin_scripts' );
 
function my_admin_scripts() {
  // wp_enqueue_script...
}

The admin_print_scripts action can be used, and you just need to append the name of the page. In the previous example scripts would load only on /wp-admin/options.php page.

Conclusion

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.

Continue reading:


Posted in: WordPress
TAGS:, , , , , , , , , , , , , , ,
Leave a comment

9 Comments

  1. Admiyn
    Sep 11th, 2009

    Great tips, and great book
    this type of tips helps a lot of new wordpress developers

  2. Doug Whitney
    May 20th, 2009

    Thanks for sharing your your expertise on developing WP plugins. They've been a great help, especially the tips on loading javascript properly and improving security with nonce.

  3. Smartphone
    Apr 20th, 2009

    Excellent advise. It really help me to add JS script. Before I read your post I spent more the 3 hours trying to add JS script into my plugin.

  4. Peter
    Mar 26th, 2009

    Quote :

    "
    if (!is_admin())

    The code above checks if the opened page is not an admin page as we do not want to load scripts there. "

    You have no idea how much that sentence helped me. It avoided me loading unnecessary Javascript files into the admin pages.

    Thank you so much and thanks for sharing this.

  5. Mike
    Feb 24th, 2009

    Awesome - this is just what I needed.

  6. sibble
    Dec 16th, 2008

    Thank you, I was looking for something like this :)

    Extremely useful!!!

  7. aminhers
    Dec 3rd, 2008

    thank you, its very useful

  8. Jake
    Dec 1st, 2008

    Thanks for the tutorial!

  9. wordpress guestbook plugin
    Dec 1st, 2008

    i tried it

Have your say

Your email is never published nor shared. Required fields are marked *

*
*

This site rewards regular commentators with do-follows links to their site.

Subscribe without commenting

About Vladimir

vladimir prelovac Hi! My name is Vladimir Prelovac. I am a computer engineer by profession and an adventurer by state of mind.

"I would love to change the world, I just don't have the source code yet."

Books by Vladimir

WordPress Plugin Devleopment Book WordPress Plugin Development: Beginner's Guide

Published by Packt Publishing, available online through Amazon. Click the image for more information.

Consulting Services

Professional WordPress solutions based on custom developed plugins and themes

Expert on-site WordPress SEO consulting and an 'out-of-the-box thinking' approach to problems