Posted By

emilbjorklund on 01/19/11


Tagged

js php wordpress widget wp


Versions (?)

Wordpress widget with JS/behaviour


 / Published in: PHP
 

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

Report this snippet  

You need to login to post a comment.