Can widgets.php invoke a js function?
-
WordPress widgets are activated in a theme’s
widgets.php
file. TheFoo_Widget
example in the WordPress Widgets API shows that widgets should call awidget
function, anupdate
function, and aform
function, with thewidget
function containing the code that will be activated when widgets are displayed.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
//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'] + $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>'; }
- The topic ‘Can widgets.php invoke a js function?’ is closed to new replies.