admin_enqueue_scripts
and wp_enqueue_script
are the preferred way to add javascript files to the dashboard.
// I'm using an anonymous function for brevity.
add_action( 'admin_enqueue_scripts', function() {
wp_enqueue_script( 'handle', plugin_dir_url( __FILE__ ) . '/script.js' );
} );
If you want to output the javascript using your PHP function however, wp_add_inline_script
doesn't seem to work. Instead, you can use admin_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 as jQuery
.
add_action( 'admin_print_scripts', function() {
// I'm using NOWDOC notation to allow line breaks and unescaped quotation marks.
echo <<<'EOT'
<script type="text/javascript">
jQuery(function($){
// Do stuff here.
});
</script>
EOT;
}, PHP_INT_MAX );