Adding custom style and javascript to Widgets

I’m currently developing a new plugin and I was in the need of using a custom stylesheet and javascript code to make the widget work.

However, I found that I can’t pre-load the files right from the widget constructor (I mean, I could , but it is not very nice/wise).  I stumbled with some answers on the web and finally I  ended up with a somewhat-clean version.  I put all the code inside a class,  and the stylesheet & javascript code is initialized calling a static function from the class.  Probably there are many other solutions out there, but I like this one the most, so I keep & share it.

/*
Plugin Name: Sample Widget
Plugin URI: x
Version: 0.0.1
Author: FZSM
Description: Simple way of style and javascript initialization
*/

//Add styles and javascript way before widget is launched
add_action ('init','sample_widget::check_widget');
//Initialize widget from here
add_action('widgets_init', create_function('', 'return register_widget("sample_widget");'));

class sample_widget extends WP_Widget {
    //Constructor
	function sample_widget() {
		$widget_ops = array('classname' => 'widget_sample_widget', 'description' => 'Sample Widget' );
		$this->WP_Widget('sample_widget', 'Sample Widget', $widget_ops);
	}

	function widget($args, $instance) {
        echo "here's the widget output";
	}

	function update($new_instance, $old_instance) { //save the widget
	}

	function form($instance) {	                    //widgetform in backend
	}

    /**
     * Checks if plugin is active and then adds style and javascript. Needs to be triggered before widget itself
     */
    static function check_widget() {
        if (is_active_widget(false,false,'sample_widget',true)) {
            //Add styles
            wp_register_style( 'sample_widget__style', plugin_dir_url(__FILE__) . 'style_widget.css'  );
            wp_enqueue_style ( 'sample_widget__style' );

            //Register scripts. this sample depends on jquery
            wp_enqueue_script('sample_widget_js', plugin_dir_url(__FILE__) . 'js_widget.js', array('jquery'), FALSE, FALSE);
        }
    }
}

1 Comment


    • Andres Castillo
      Reply Cancel Reply
    • May 19, 2014

    4 hours looking for this, tks for shear

Leave a Reply

Your email address will not be published Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*