Can widgets.php invoke a js function?

WordPress widgets are activated in a theme’s widgets.php file.

The Foo_Widget example in the WordPress Widgets API shows that widgets should call a widget function, an update function, and a form function, with the widget function containing the code that will be activated when widgets are displayed.

Read More

Is there a way to have the widget function invoke a JavaScript function stored in a separate js file?

Here’s what I have tried with the Foo_Widget example linked above. The “fooey!” alert works fine, but instead of displaying a widget all that appears in the widget space is the word “undefined.” Any idea what I’m doing wrong? Thanks!

Header Text

<?php wp_enqueue_script( 'foo', get_template_directory_uri()."/js/foo.js" ); ?>

foo.js

function foo( $args, $instance ) {

    alert("fooey!");

    document.write($args['before_widget']);

    if (!empty($instance['title'])) {
        document.write($args['before_title'].apply_filters('widget_title', $instance['title']).$args['after_title']);
    }

    document.write("Hello world!");
    document.write($args['after_widget']);
}

Updated Widget Function

public function widget( $args, $instance ) {
    echo '<script type="text/javascript">foo(' . $args . ',' . $instance . ')' . ';</script>';
}

Related posts

Leave a Reply