0

I need to load a separate js file into a widget and just can't get it to work. So far I have

if ( is_active_widget( false, false, $this->id_base, true ) ) {
    function tab_widget_scripts() {
        wp_register_script( 'tabs', plugins_url( 'tabs.js', __FILE__ ), array(), false, true );
        wp_enqueue_script( 'tabs.js' );
    }
}

in my function __construct() and then

do_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );

inside public function widget( $args, $instance ). Can anyone tell me what I'm doing wrong please?

1

2 Answers 2

1

There are 3 issues.

Firstly, you're calling do_action, triggering the action:

do_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );

When actually, you want to add your function to it, not trigger it. You should be doing this:

add_action( 'wp_print_footer_scripts', 'tab_widget_scripts' );

Secondly, you're registering this script:

tabs

Then enqueuing this script:

tabs.js

Clearly they don't match, in the same way that if I give you the ingredients for cake then tell you to make a latte, it isn't going to work.

Thirdly, you only define the function if the widget is shown on the frontend. This is a little odd, instead you should use add_action on your function in your widget class, and always define it, saving yourself an unnecessary call to is_active_widget

1
  • Thanks Tom, that's a great explanation and all sorted now. Nov 27, 2014 at 10:38
1

do_action should be add_action - you're adding a function to the queue, not executing all functions hooked to the action. That said, you don't have to hook a separate function, you can just enqueue directly in the widget function if you want.

1
  • Thanks Milo, that's a lot more simple than what I was trying. Nov 27, 2014 at 10:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.