Rishi
Rishi

Reputation: 2027

How do I include a javascript file in Wordpress admin Widgets

I have created a widget for wordpress. The form of the widget has some input boxes. Now, I want to add a custom input box which uses a javascript file I downloaded from http://jscolor.com/

Now, the problem is, it is not working. I have registered the javascript file like this in the form function of the WP_Widget class.

require_once('index.php');
add_action('admin_enqueue_scripts', 'pw_load_scripts');

The pw_load_scripts function is in index.php

function pw_load_scripts() {
    wp_register_script('custom-js', plugin_dir_url(__FILE__).'scripts/jscolor.js');
    wp_enqueue_script('custom-js');
}

After all these, it is not working. What is the correct way to do this task?

My error.log has this error

[Mon Oct 07 21:37:30.591896 2013] [:error] [pid 14853] [client 127.0.0.1:42453] PHP Fatal error:  Cannot redeclare _wp_menu_output() (previously declared in /var/www/wordpress/wp-admin/menu-header.php:36) in /var/www/wordpress/wp-admin/menu-header.php on line 36

Thank you

Upvotes: 3

Views: 2216

Answers (2)

manishie
manishie

Reputation: 5322

Try removing:

require_once('index.php');

I'm not sure where you got this from. It appears to be trying to reload wordpress' index.php file.

Upvotes: 1

brasofilo
brasofilo

Reputation: 26055

The correct hook is admin_print_scripts 1 to enqueue styles and scripts.

Note that admin_footer and admin_head also accept the same screen targeting 'actionname-$hook':

add_action( 'admin_print_scripts-widgets.php', 'admin_enqueue_so_19228543' );

function admin_enqueue_so_19228543()
{
    wp_enqueue_script( 
            'my-script', 
            plugins_url( '/my-script.js', __FILE__ ), 
            array(), // dependencies
            false, // version
            true // on footer
    );
    wp_enqueue_style( 
        'my-style', plugins_url( '/my-style.css', __FILE__ ) 
    );

}

1 The Codex is saying otherwise, but I was pretty sure this was an official stance. I'm researching and will report back.


update

I cannot find any reference to admin_print_scripts being the correct hook, although it works and I've seen used this way many times. For completeness, this is how admin_enqueue_scripts works:

add_action( 'admin_enqueue_scripts', 'admin_enqueue_so_19228543' );

function admin_enqueue_so_19228543( $hook )
{
    if( 'widgets.php' != $hook )
        return;

    wp_enqueue_script( 
            'my-script', 
            plugins_url( '/my-script.js', __FILE__ ), 
            array(), // dependencies
            false, // version
            true // on footer
    );
    wp_enqueue_style( 
        'my-style', plugins_url( '/my-style.css', __FILE__ ) 
    );

}

Related: Difference between do_action('admin_enqueue_scripts', $hook_suffix) and do_action(“admin_print_styles-$hook_suffix”) syntax

Upvotes: 2

Related Questions