How to enqueue script if widget is displayed on page?

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...
    }
?>

Leave a Comment