I created a widget that uses a jquery plugin, and I used is_active_widget to enqueue the script, it’s working fine but it’s also including the script even on pages that doesn’t show this widget.
so is there a way to only enqueue the script if this widget is showing ?
thanks in advance.
You should be able to call
wp_enqueue_script()
as part of your Widget output.Edit
Quick-and-dirty, using the bare-bones Widgets API class example:
Add your
wp_enqueue_script()
call inline, within your Widget’s output – i.e. within thepublic function widget()
:If the script needs to go in the
<head>
section:Otherwise, Chip Bennett’s solution will work for queuing it in the footer.
The
$did_script
static variable is not required, I used it just to avoid further unnecessary calls towp_enqueue_script
if there are multiple widget instances on the page…Pierre,
The way I handle this is with
wp_enqueue_script
andwp_dequeue_script
, and use a instance variable$is_active
in the Your_Widget classSo do the
wp_enqueue_script
based onis_active_widget
which enqueues the script on all pages but with the footer parameter set to true. Note the dequeue is run at a priority to make sure it runs before the scripts are output.}
Then in the widget function indicate if the widget is active on that page
Then in the footer dequeue the script if the widget is not active on that page
This approach of enqueue then dequeueing if unused also works well for plugins that define shortcodes which require scripts
I considered ‘wp_footer’ hook because this hook is executed at footer,and is probably the best way to add scripts only where the widget is used.