Create a Widget in WordPress

 

Let’s ensamble the plugin step by step so you can see how is the workflow here. Let’s start by adding a class:

class myplugin_newsletter_subscriber_set_widget extends WP_Widget { 
}

Inside this class we need to create four functions:

class myplugin_newsletter_subscriber_set_widget extends WP_Widget { 
function __construct() {}
function form($instance) {}
function update($new_instance, $old_instance) {}
function widget($args, $instance) {}
}

You will see that there are some variables declared inside these functions, these values will be automatically coming from wordpress.

Now let’s populate these functions one per one:

Function Construct

Here we will construct our widget, assign an ID and also give it a name and a description

// constructor
function __construct() {
   parent::__construct(
     'my_custom_plugin_id', // Base ID
     __('My plugin Name', 'translation'), // Name
     array( 'description' => __( 'My plugin description', 'translation' ), ) // Args
   );
 }

Function Form

function form($instance) { 
 if ( isset( $instance[ 'title' ] ) ) {
 $title = $instance[ 'title' ];
 }
 else {
 $title = __( 'New title', 'text_domain' );
 }
 ?>
 <p>
 <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
 <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
 </p>
 <?php 
 }

Function Update

function update($new_instance, $old_instance) {
 $instance = array();
 $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

 return $instance;
}

Function Widget

// widget display
function widget($args, $instance) {
 $title = apply_filters( 'widget_title', $instance['title'] );

 if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title'];
 ?>
 <div>
   Show my widgetcontent on here
 </div>
 <?php
 endif;
}

With these 4 functions you can build your widget as you want and have it show on your sidebar or on any other widget space you have created on your template.

 

Leave a Reply