public

WidgetWithBehaviorScript: Template for a WordPress widget which enqueues an accompanying behavior script; script only output if widget is rendered.

  • Download Gist
WidgetWithBehaviorScript.widget.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
<?php
 
class WidgetWithBehaviorScript extends WP_Widget {
function __construct() {
parent::__construct(__CLASS__, 'Widget with Accompanying Behavior Script', array(
'classname' => __CLASS__,
'description' => "This WordPress widget serves as a pattern for how to enqueue a script only if the widget is actually rendered."
));
// Enqueue the .js script which accompanies the widget
wp_enqueue_script(
__CLASS__,
trailingslashit(get_template_directory_uri()) . __CLASS__ . ".js",
array('jquery'), // Whatever you want
filemtime(trailingslashit(TEMPLATEPATH) . __CLASS__ . '.js'),
true // Must be true (in_footer)
);
// Schedule an action to remove the enqueued script; this action is
// removed if the widget is actually rendered (if the widget() is called)
add_action("wp_print_footer_scripts", array(__CLASS__, 'remove_enqueued_script'));
}
/**
* Remove the enqueued script
*/
function remove_enqueued_script(){
wp_deregister_script(__CLASS__);
}
function widget($args, $instance) {
// Abort the scheduled removal of the enqueued script because the widget is being rendered
remove_action("wp_print_footer_scripts", array(__CLASS__, 'remove_enqueued_script'));
extract($args, EXTR_SKIP);
global $Shopp;
echo $before_widget;
echo $before_title;
# ...
echo $after_title;
# ...
echo $after_widget;
}
 
function update($new_instance, $old_instance) {}
function form($instance){}
}
 
?>

This isn't needed in 3.3 due to [18446] . Just add wp_enqueue_script( '{handle}', '{src}', array( '{deps}' ), '{ver}', true ) to the widget() function. That's it!

Thanks for the heads up!

No Problem. The guy that was having problems with it forked: https://gist.github.com/1172287
Also, I found WHY it broke and we should have it fixed before 3.3 is released. Still, it would still be better to do it right since this hack isn't needed anymore.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.