Introduction

Widget is a small block that performs a specific function. You can add widgets in sidebars also known as widget areas on your web page. Widgets is easy to install and the list of widget available widgets and widget areas by going to the Appearance » Widgets

Default widgets including categories, tag cloud, navigation menu, calendar, search, recent posts etc. If you drag the recent posts widget in a widget area, then it will contain a list of recent posts in Wordpress.

How to create widget

Step 1: To open function.php file and paste below code.

  1. // Creating the widget
  2. class wpb_widget extends WP_Widget {
  3. function __construct() {
  4. parent::__construct(
  5. // Base ID of your widget
  6. 'wpb_widget',
  7. // Widget name will appear in UI
  8. __('WPBeginner Widget', 'wpb_widget_domain'),
  9. // Widget description
  10. array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), )
  11. );
  12. }
  13. // Creating widget front-end
  14. // This is where the action happens
  15. public function widget( $args, $instance ) {
  16. $title = apply_filters( 'widget_title', $instance['title'] );
  17. // before and after widget arguments are defined by themes
  18. echo $args['before_widget'];
  19. if ( ! emptyempty( $title ) )
  20. echo $args['before_title'] . $title . $args['after_title'];
  21. // This is where you run the code and display the output
  22. echo __( 'Hello, World!', 'wpb_widget_domain' );
  23. echo $args['after_widget'];
  24. }
  25. // Widget Backend
  26. public function form( $instance ) {
  27. if ( isset( $instance[ 'title' ] ) ) {
  28. $title = $instance[ 'title' ];
  29. }else {
  30. $title = __( 'New title', 'wpb_widget_domain' );
  31. }
  32. // Widget admin form
  33. ?>
  34. <p>
  35. <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
  36. <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 ); ?>" />
  37. </p>
  38. <?php
  39. }
  40. // Updating widget replacing old instances with new
  41. public function update( $new_instance, $old_instance ) {
  42. $instance = array();
  43. $instance['title'] = ( ! emptyempty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
  44. return $instance;
  45. }
  46. } // Class wpb_widget ends here
  47. // Register and load the widget
  48. function wpb_load_widget() {
  49. register_widget( 'wpb_widget' );
  50. }
  51. add_action( 'widgets_init', 'wpb_load_widget' );

Step 2: Check widget in widgets area.