How to create WordPress widget


1. Widget Class name should be ended with ‘_Widget’ only.

2. Class should extends ‘WP_Widget’

3. Have four functions

a) __construct()
b) widget($args,$instance)
c) form($instance)
d) update($new_instance,$old_instance)

1. Class

class contains the name with ‘__Widget’ and extends the ‘WP_Widget’

Class TW_Widget extends WP_Widget{

}

2. __construct()

__construct() is constructor for this class widget. This code will be run every time widget is loaded, when activated and updated.

public function __construct(){
parent::__construct(
‘tw_widget’, // Base ID
‘Twitter Widget’, // Name
array( ‘description’ => __( ‘A Twitter Widget’, ‘text_domain’ ), ) // Args
);
}

3. widget($args,$instance)

widget($args,$instance) function contains the code that will be rendered to the sidebar when widget is added and that will be visible to website visitors.

public function widget($args,$instance){
$title = apply_filters( ‘widget_title’, $instance[‘title’] );
echo $args[‘before_widget’];
echo __( ‘Hello, World!’, ‘text_domain’ );
echo $args[‘after_widget’];
}

4. form($instance)

form($instance) function contains the setting page on WordPress widget admin screen. That will be visible in the Appearance -> Widgets. This method called the

public function form($instance){
if(isset($instance[‘title’])){
$title = $instance[‘title’];
}else{
$title = __(‘New Widget Title’,’text_domain’);
}
?>
<p>
<label for=”<?php echo $this->get_field_name( ‘title’ ); ?>“><?php _e( ‘Widget 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

}

5. update($new_instance,$old_instance)\

update($new_instance,$old_instance) function called when click on “Save” option in the settings page in the admin secion/screen. And those details will save into database by options.

public function update($new_instance,$old_instance){
$instance = array();
$instance[‘title’] = ( ! empty( $new_instance[‘title’] ) ) ? strip_tags( $new_instance[‘title’] ) : ;
return $instance;
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s