Add custom Javascript to a WordPress plugin’s admin page and pass PHP variables to it

6 Jan

I’m almost a WordPress geek by now, but I confess I always had trouble including a Javascript file with my own custom scripts in it. And I always used ‘wp_register_script’ and ‘wp_enqueue_script’ the wrong way. What’s worse, I literally echoed out the path to the Javascript file by assigning it to a variable first. See how I did it:

<?php
//blah blah code code....
.
.
.
//This is where I want to use my Javascript file
                $pluginurl = dirname(plugin_basename(__FILE__)).'/';
		$helperscripts = WP_PLUGIN_URL.'/'.$pluginurl.'js/scripts.js';
		echo "<script src='".$jquery."' type='text/javascript' charset='utf-8'></script>
			<script src='".$helperscripts."' type='text/javascript' charset='utf-8'></script>";
?>


This worked, but what happened sometimes is that I got the very cruel, ‘The plugin generated X characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin’ error. And even if it did work, the script was included on all the pages, even where it wasn’t used. Precisely, I just wanted it for my plugin’s admin area, and it got included on all the pages! The right way to include it only on the plugin page was just around the corner, and I found it by a little bit of googling and experimenting with the code.

Let’s see how to include/enqueue a Javascript file, say ‘scripts.js’ on our plugin’s admin page. We use the ‘admin_print_scripts’ action hook and ‘wp_enqueue_script’ to get our job done. This is how it should be done:
First add the plugin options page via the ‘admin_menu’ hook.

<?php
   add_action('admin_menu', 'plugin_admin_menu');
  function plugin_admin_menu()
  {
    add_options_page('Plugin Admin Page', 'Plugin Admin Page', 10, 'plugin-admin-page', 'plugin_admin_page');
  }
?>

The 4th parameter in ‘add_options_page’ is the page slug. For our plugin, its ‘plugin-admin-page’. Now we use the ‘admin_print_scripts’ action hook along with the plugin page slug. The page slug is used to tell this hook that we want the scripts to be included only on the plugin page whom the page slug belongs to.

<?php

   add_action('admin_menu', 'plugin_admin_menu');
   function plugin_admin_menu()
   {
      add_options_page('Plugin Admin Page', 'Plugin Admin Page', 10, 'plugin-admin-page', 'plugin_admin_page');
   }

   add_action('admin_print_scripts-settings_page_plugin-admin-page', 'add_my_scripts');
   function add_my_scripts()
   {
       //We can include as many Javascript files as we want here.
       wp_enqueue_script('pluginscript', plugins_url('/js/script.js', __FILE__), array('jquery'));
   }
?>

The parameters used in the wp_enqueue_script function are:

  1. pluginscript: This is the identifier for our script.
  2. plugins_url(‘/js/script.js’): The parameter here assumes that we have a folder ‘js’ inside our plugin’s folder, and the ‘script.js’ file is inside this folder. Previously, the path was given as ‘WP_PLUGIN_URL.’//’. But this is unsafe, so now we use the ‘plugins_url’ function.
  3. __FILE__: Just write it this way!
  4. array(‘jquery’): This means our custom Javascript code depends on jQuery to run.

That’s it! The ‘script.js’ file is now included only on our plugin’s admin page!
Next part is to pass PHP variable/s to the Javascript file. This is done using the ‘wp_localize_script’ function. ‘wp_localize_script’ allows us to pass PHP variable/s from our plugin’s main file to the Javascript functions in our enqueued Javascript file along with a handle which is used to access these variables in the Javascript functions.
Suppose we have a PHP variable, say ‘$name’ which we want to alert out based on some action.

<?php

   add_action('admin_menu', 'plugin_admin_menu');
   function plugin_admin_menu()
   {
      add_options_page('Plugin Admin Page', 'Plugin Admin Page', 10, 'plugin-admin-page', 'plugin_admin_page');
   }

   add_action('admin_print_scripts-settings_page_plugin-admin-page', 'add_my_scripts');
   function add_my_scripts()
   {
       //We can include as many Javascript files as we want here.
       wp_enqueue_script('pluginscript', plugins_url('/js/script.js', __FILE__), array('jquery'));
   }

   $name = 'Keyser Söze';
   // This allows us to pass PHP variables to the Javascript code. We can pass multiple vars in the array.
   wp_localize_script( 'MyJQueryHandle', 'custom', array(
	  	                                                           'name' => $name
		                                                         ));

?>

Parameters here are:

  1. MyJQueryHandle: The identifier for our Javascript code/file.
  2. custom: The handle that we use for accessing the PHP variables in our Javascript code. We can name it anything that suits the job.
  3. array(…): We access the ‘$name’ parameter using the handle as ‘custom’.’name’ in our Javascript code.

And our Javascript file should look like this:

/**
 * Handle: MyJQueryHandle     //Read the 'wp_localize_script' function above and you'll know what this is!
 * Version: 0.0.1
 * Deps: $jq                        
 * Enqueue: true
 */
 
 $jq = jQuery.noConflict();     //We use $jq here because we are using jQuery.noConflict to avoid conflicts with other Javascript libraries that use '$'.

 var name = custom.name;     //Note the handle name and the parameter name that we had declared in 'wp_localize_script'.

$jq('#some_button_identifier').click(function(){
                                                                alert('Hey '+name+', did you get it sparky?');
                                                             }
                                             );

If all went well and you followed the steps correctly, you should now be able to include Javascript files only on the plugin pages and be able to pass PHP variables to it…!
Hope this helps someone! In case of doubts, queries and suggestions (they’re needed and are welcome cuz I’m still a very lame programmer! :P), you can contact me on Twitter or email me at rutwick@amiworks.com. Leave a comment.

Thanks… Happy WordPressing!

About these ads

2 Responses to “Add custom Javascript to a WordPress plugin’s admin page and pass PHP variables to it”

  1. Fredrick Tillman July 28, 2011 at 8:45 pm #

    Thank Rutwick, I am struggling to reach a level of proficiency with wordpress, and at the same time, keep up with changes.

    • Rutwick Gangurde July 29, 2011 at 2:52 am #

      You’re welcome!
      I appreciate your efforts to be a good WP developer and best of luck for it!
      WordPress is awesome! Will take some time to get deeper into it, but once you’re in, you won’t feel like switching! Start with the easier things, like simple theme development functions, then slowly move to plugin development (which is already made very easy by WP’s action and filter system), user management, custom posts, settings API etc.
      Any help you need with WP or you’re stuck somewhere, feel free to ask me at mail@rutwick.com or @tweetrut. I’ll try my best to help you! :)

      Regards,
      Rutwick

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: