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…
You can simply put your init code within the constructor of the class. For example:
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.
Your code is PHP4 style. PHP4 styled code should not be used anymore. And just putting some functions inside a class construct is not OOP. If you want to write reusable code, separate your code.
For example:
This class can be reused for every widget. The idea behind OOP is reusing your code by writing data constructs with additional function. Not using class constructs because somebody say it is good style.
The class could be used like this: