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.
Use the
admin_enqueue_scripts
action and thewp_enqueue_script
method to add custom scripts to the admin interface.This assumes that you have
myscript.js
in your plugin folder. Change accordingly. Themy_custom_script
handle should be unique for your module and script.There is a snippet for Your functions.php file :
Works fine on WordPress 3.2.1.
admin_enqueue_scripts
andwp_enqueue_script
are the preferred way to add javascript files to the dashboard.If you want to output the javascript using your PHP function however,
wp_add_inline_script
doesn’t seem to work. Instead, you can useadmin_print_scripts
to directly echo out the script, including the script tags themselves. Just ensure to set the priority high so that it loads after any required libraries, such asjQuery
.If you want to get fancy and filter where you want to load the file or not, best to use
get_current_screen
.Directly adding wp_enqueue_script to your code doesn’t include the script in new versions of WordPress (5.0 above).
The better way is to register the script with wp_register_script first to create a handle and then enqueue that handle.
Somehow the accepted answer didn’t work for me. Here is another solution I didn’t found in the answers and this is what did it for me, WP 5.x, adding some css and js for my backend…
By using the admin enqueue script hook you can easily add the script file for the admin panel.