What is the correct way to build a widget using OOP

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 Comment