2

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!

1 Answer 1

1

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'));
Sign up to request clarification or add additional context in comments.

1 Comment

Using the load-widgetsphp action didn't work, however, using widgets_init did. Thanks for advice anyhow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.