How to add custom javascript to WordPress Admin?

Nacho picture Nacho · Jul 24, 2010 · Viewed 95.3k times · Source

I want to add some custom jquery code to the Edit Post page, something really simple like showing a div when someone presses Publish.

The only restriction is that I want to achieve this through the use of a plugin, not hacking the admin template files.

I've tried echoing some script tags using some actions but it doesn't seem to be the way.

Answer

Tim picture Tim · Feb 20, 2014

Use the admin_enqueue_scripts action and the wp_enqueue_script method to add custom scripts to the admin interface.

This assumes that you have myscript.js in your plugin folder. Change accordingly. The my_custom_script handle should be unique for your module and script.

function my_enqueue($hook) {
    // Only add to the edit.php admin page.
    // See WP docs.
    if ('edit.php' !== $hook) {
        return;
    }
    wp_enqueue_script('my_custom_script', plugin_dir_url(__FILE__) . '/myscript.js');
}

add_action('admin_enqueue_scripts', 'my_enqueue');