Loading custom JavaScript files in the Wordpress widgets admin panel

I'm writing a new Wordpress plugin that includes a widget. The widget configuration options require jQuery code to fetch them from a 3rd party server via JSONP, and attach events so that if one dropdown changes, say category, it dynamically changes the content of another dropdown, say subcategory.

To achieve this effect, I need to load some custom JavaScript files in the widget admin panel (the options that show after the user has dragged and dropped the widget to the relevant sidebar in the admin panel).

What is the correct way of doing so? I've tried the following code in my plugin class, but it doesn't seem to load the files:

class MyPlugin {

    function __construct() {
        add_action('admin_init', array(&$this, 'admin_init'));
        add_action('admin_head', array(&$this, 'admin_load_scripts'));
    }

    function admin_init() {
        wp_register_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
        wp_register_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));
    }

    function admin_load_scripts() {
        wp_enqueue_script('jsonp');
        wp_enqueue_script('my_utils');  
    }

}

Thanks in advance!

Answers


It's probably because the hook admin_head is too late to queue - try using load-widgets.php instead (this will also mean your scripts don't appear on every admin page!).

And as a side note, you don't need to register, then enqueue - you can do both in one call;

wp_enqueue_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
wp_enqueue_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));

Need Your Help

Passing IEnumerable across appdomain boundaries

c# .net performance remoting appdomain

Is it generally a bad idea to pass an IEnumerable across appdomain boundaries?

“puff of smoke” effect javascript sprite animation

javascript animation settimeout jquery-animate

This code and animation works perfectly on jQuery 1.4.4 and below, but not on later versions. Could anyone shed some light on this issue and help with a version that works with latest jQuery. I have

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.