Create New Widget in WordPress

Sometimes we need to create a widget in WordPress Template, to create a new widget just drop this line in your theme function.php file, and make changes as required.

PHP
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849

<?php
//widget example
add_action( 'widgets_init', 'register_my_test_widget' ); //function name here
function register_my_test_widget() { //register function
    register_widget( 'this_is_test_widget' );
}
class this_is_test_widget extends WP_Widget{ //widget class
	function __construct() {
		parent::__construct(
			'this_is_test_widget', // ID
			__('Test Widget', 'text_domain'), // Name
			array( 'description' => __( 'Test widget for testing WordPress widget', 'text_domain' ), )
		);
	}
	public function widget( $args, $instance ) {
		$title = apply_filters( 'widget_title', $instance['title'] );
		echo $args['before_widget'];
		if ( ! empty( $title ) )
			echo $args['before_title'] . $title . $args['after_title'];
			######### widget content start ########
			echo '
<div>';
			echo 'widget Content goes here';  //put your PHP functions or text here
			echo '</div>
';
			######### widget content end ##########
			echo $args['after_widget'];
	}
	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		}
		else {
			$title = __( 'New title', 'text_domain' );
		}
		?>

		<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 ); ?>">
		
		<?php 
	}
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
		return $instance;
	}
}