How can I include JavaScript that use jQuery on admin side

The problem is that you are loading your script before jQuery has been loaded.

Do not print scripts directly.

You should (register and then) enqueue them using the provided API. jQuery is already a registered script, so you can just enqueue it (say on the admin_enqueue_scripts hook).

However you only need to load jQuery if you are loading a custom script that requires it, in which case you should enqueue your custom script and add jQuery as a dependency. WordPress will then handle the loading of the scripts and in the correct order:

add_action('admin_enqueue_scripts','wptuts53021_load_admin_script');
function wptuts53021_load_admin_script( $hook ){
    wp_enqueue_script( 
        'wptuts53021_script', //unique handle
        get_template_directory_uri().'/admin-scripts.js', //location
        array('jquery')  //dependencies
     );
}

Side remarks

  • Use get_template_directory_uri() rather than get_bloginfo()
  • Use the passed $hook (which will be edit.php, post.php, post-new.php etc) and get_current_screen() to determine if you are on a page that requires your script to be loaded. Only load scripts when you actually need them.

E.g (Codex example):

function my_enqueue($hook) {
    //Load only on edit.php pages
    //You can use get_current_screen to check post type
    if( 'edit.php' != $hook )
        return;
    wp_enqueue_script( 'my_custom_script', plugins_url('/myscript.js', __FILE__) );
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );

Leave a Comment