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:
<?php
class wpse48337_Widget extends WP_Widget {
public function __construct() {
// widget actual processes
}
public function form( $instance ) {
// outputs the options form on admin
}
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
public function widget( $args, $instance ) {
// outputs the content of the widget
}
}
register_widget( 'wpse48337_Widget' );
?>
Add your wp_enqueue_script()
call inline, within your Widget’s output – i.e. within the public function widget()
:
<?php
public function widget( $args, $instance ) {
// outputs the content of the widget
// Enqueue a script needed for
// the Widget's output
wp_enqueue_script( 'jquery-pluginname', $path, $deps );
// Rest of widget output goes here...
}
?>