Adding Javascript to WordPress Admin

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

You can add javascript to WordPress admin without touching WordPress core.  In other words, do not touch anything inside wp-admin folder.  Otherwise your customization will be overwritten in the next WordPress core update.

You want to add the “admin_init” action hook to the theme’s functions.php

Add the following code to the bottom of the functions.php file…

admin_init hook

admin_init hook

The WordPress codex for this hook states ..

“admin_init is triggered before any other hook when a user accesses the admin area. This hook doesn’t provide any parameters, so it can only be used to callback a specified function.”

When admin_init is triggered, it will call the function “enqueue_admin_script”.  This is an arbitrarily named function that you choose.  Because you will be constructing that function definition in the next line.  In our function definition for enqueue_admin_script, we call the built-in wordpress function wp_enqueue_script to add our script to system.

The first parameter of wp_enqueue_script is the name of our script (without the .js).  The second parameter is the uri path to that script.  The third parameter is the dependencies that the script might depend on.  Here we specify none with an empty array.  If our script depended on jQuery, we would put

array( 'jquery' )

The fourth parameter the version of the script.  The fifth parameter is true if we want the script placed in the footer.

For demo, create our admin-script.js in the js folder of our template directory and just put …

alert(‘in admin’);

And see that this is alerted only when we are in the admin pages and not in the front-end site.