How to Create a New Custom Widget in WordPress

WordPress provides some default widgets to display extra content on the website. However, we can also create custom widgets when required.

Every widget has its own unique functionality on the website. Otherwise, there would be no need to create a new widget.

Add a New Widget in WordPress

WordPress provides some default widgets like categories, archives, tags, search, etc. In addition, some WordPress themes provide extra widgets according to theme purpose and functionality. But, sometimes these widgets are not enough. So, let’s create a new one. Follow the below steps to create a new widget.

Step 1: Go to Theme Editor and Select a Theme

First, open WordPress admin panel and open the Theme Editor window and select a theme in which you have to add a new widget.

Step 2: Register a New Widget

After that, open the functions.php file of your selected theme. Now copy and paste the below code at the end of the file.

CODE

function errorsea_widget() {register_widget( 'errorsea_new_widget' );}

add_action( 'widgets_init', 'errorsea_widget' );

class errorsea_new_widget extends WP_Widget {

	function __construct() {

	parent::__construct(

	// widget ID

	'errorsea_new_widget',

	// widget name

	__('Widget Title', ' errorsea_domain'),

	// widget description

	array( 'description' => __( 'Widget Description', 'errorsea_domain' ), )

	);

	}

	public function widget( $args, $instance ) {

	$title = apply_filters( 'widget_title', $instance['title'] );
	echo $args['before_widget'];

	//if title is present

	if ( ! empty( $title ) )
		echo $args['before_title'] . $title . $args['after_title'];

	// add your custom code here to display in widget

	echo $args['after_widget'];

	}

	public function form( $instance ) {

	if ( isset( $instance[ 'title' ] ) )

	$title = $instance[ 'title' ];

	else

	$title = __( 'Widget Title', 'errorsea_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
}

public function update($new_instance, $old_instance)
{

    $instance = array();

    $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';

    return $instance;

}

}

Step 3: Use the New Widget

Now our new widget is ready to use in our website. Just go to the widgets section and add the new widget anywhere on your website and save.

Read Also: How to Remove “Category:” From Category Archive Pages in WordPress

Conclusion

I hope now you can create a new widget your self with your desired output and functionality. You can explore more and create something creative.

Happy coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *