Why are admin scripts not printed

I am trying to enqueue/print scripts in the admin area. But they dont seem to appear.

add_action('admin_init', function() {
    add_meta_box('portfolio-meta', 'Details', 'portfolio_metabox_details', 'portfolio');

    wp_register_script('jqeury-validate', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js');
    wp_enqueue_script('jquery-validate');
    wp_register_script('ae-admin', get_bloginfo('template_directory') . '/js/admin.js', array('jquery', 'jquery-validate'));
    wp_enqueue_script('ae-admin');
    wp_localize_script('ae-admin', 'WpAjax', array(
            'AjaxUrl' => admin_url('admin-ajax.php')
    ));
    wp_register_style('ae-validate', get_bloginfo('template_directory') . '/css/validate.css');
    wp_enqueue_style('ae-validate');
});

But my script (admin.js) does not seem to get printed. I even tried to put those in ‘init’ instead of ‘admin_init’ still I dont see my scripts … why is that? How can I debug?

4 Answers
4

Use the admin_enqueue_scripts hook instead of admin_init

Note: you should use hooks that target admin pages as specifically as possible. e.g.:

  • Plugins: Use the admin_print_scripts-{plugin-page} hook
  • Themes: Use the admin_print_scripts-{theme-page} hook (where {theme-page} is whatever string you use in the add_theme_page() call)
  • Custom Post-Type Edit Page: Use the admin_print_scripts-edit.php hook,

For Custom Post Types, inside your function, do something like the following:

global $typenow;
if( 'portfolio' == $typenow ) {
    // wp_enqueue_script() calls go here
}

(h/t t31os)

Leave a Comment