I am working on a simple search form widget, with a built in autocomplete capability (You can download the current version here). The plugin is working, but I am currently rewriting all the code using OOP. One of the problems I came across was the fact the a WordPress Widget is already a part of the WP_Widget class.
I can divide the code into 2 classes. The first one loads all the scripts and css, and initializes the widget. Here is the outline of the code:

class wdSearchForm {

        public function __construct() {
            // Action hook to load widget
            // Register and enqueue styles
            // Register and enqueue scripts
        }

        // register widget in WordPress so that it is available under the widgets section
        public function wd_searchform() {
            register_widget( 'wd_searchform' );
        }
}

And here is the outline to the widget class:

class wd_searchform extends WP_Widget {

    // Constructor
    function wd_searchform() {

    }

    // The widget itself
    function widget( $args, $instance ) {
        // The widget code
    }

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

    function form( $instance ) {
        //Set up widget settings.
    }
}

I would like to combine the two, in order to use wp_localize_script and load the script with the widget options. How should I do that? Any suggestions are welcome, even if you’ll tell me i’m totally in the wrong direction…

2 s
2

You can simply put your init code within the constructor of the class. For example:

class myWidget extends WP_Widget{

    function myWidget(){
       // Init code here
    }

    function widget( $args, $instance ) {
       // The widget code
       wp_enqueue_script(...);
       wp_enqueue_style(...);

   }

   // Over methods...

}

register_widget('myWidget');

My preference is to actually put the enqueue calls within the shortcode handling function to avoid the overhead and potential conflicts associated with loading JavaScript and stylesheets that aren’t being used on a given page.

Leave a Reply

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