What is a widget in WordPress?

WordPress widgets are the combination of some code which is made for a specific purpose but use dynamically. You can create a custom widget in WordPress & display in different places of your theme. WordPress provides many default widgets. To view them go to admin dashboard Appearance >> Widgets. You will see here Archives, Calendar, Categories, Meta, and many more. These are the WordPress default widget. You can use them on your sidebar. If your theme doesn’t have sidebar you have to create it. It’s very easy. I will show later.

How to Create a Custom Widget?

Sometimes we may need to create our own widget & display them with our own styles. For this purpose, WordPress provides Widgets API to create custom widget. To follow the official documentation follow this link. Here let’s see how to create a custom widget.

class em_custome_Widget extends WP_Widget {

    public function __construct() {
        // Here the actual widget processes
    }

    public function form( $instance ) {
        // Here codes for taking the inputs from admin widget area
    }

    public function update( $new_instance, $old_instance ) {
        // Here codes for saving the data to database which was taken from the upper section
    }

    public function widget( $args, $instance ) {
        // Here codes for displaying the outputs on your theme
    }

}

This code creates the widget but it is still not registered. So it needs to be registered. Here we need to use ‘widgets_init’ action hook.

function em_custom_widgets_register() {
  register_widget( 'em_custome_Widget' );
}
add_action( 'widgets_init', 'em_custom_widgets_register' );
If want to create your own sidebar for displaying the widget to a specific location you will need to create your own sidebar. Paste this snippet to your functions.php.

  function em_custom_sidebar($id){
    register_sidebar(array(
      'name' => 'Your Sidebar',
      'id' => 'sidebar',
      'before_widget' => '<div class="block side-widget">',
      'after_widget' => '</div>',
      'before_title' => '<h3>',
      'after_title' => '</h3>'
    ));    
  }
  add_action('widgets_init', 'em_custom_sidebar');

Custom Recent Posts Widget :

Let’s think we need to create our own recent posts widget and style it as we want.

class em_Widget_Recent_Posts extends WP_Widget {

  /**
   * Sets up a new Recent Posts widget instance.
   */
  public function __construct() {
    $widget_ops = array(
      'classname' => 'em_widget_recent_entries',
      'description' => __( 'Your site&#8217;s most recent Posts.' ),
      'customize_selective_refresh' => true,
    );
    parent::__construct(
      'em_recent_post_id', // Base ID
      __( 'EM Recent Posts', 'em_recent_post_widget' ), // Name
      array( 'description' => __( ' &  visitors will calculate the total cost.', 'em_cost_calculator_widget' ), ) // Args
    );
  }

  /**
   * Outputs the settings form for the Recent Posts widget.
   */
  public function form( $instance ) {
    $title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
    $number    = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
    $show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false;
?>
    <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 $title; ?>" /></p>

    <p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
    <input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" /></p>

    <p><input class="checkbox" type="checkbox"<?php checked( $show_date ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" />
    <label for="<?php echo $this->get_field_id( 'show_date' ); ?>"><?php _e( 'Display post date?' ); ?></label></p>
<?php
  }

  /**
   * Handles updating the settings for the current Recent Posts widget instance.
   */
  public function update( $new_instance, $old_instance ) {
    $instance = $old_instance;
    $instance['title'] = sanitize_text_field( $new_instance['title'] );
    $instance['number'] = (int) $new_instance['number'];
    $instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false;
    return $instance;
  }

  /**
   * Outputs the content for the current Recent Posts widget instance.
        */
  public function widget( $args, $instance ) {
    if ( ! isset( $args['widget_id'] ) ) {
      $args['widget_id'] = $this->id;
    }

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

    /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
    $title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

    $number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 3;
    if ( ! $number ) {
      $number = 3;
    }
    $show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;

    /**
     * Filters the arguments for the Recent Posts widget.
                */
    $r = new WP_Query( apply_filters( 'widget_posts_args', array(
      'posts_per_page'      => $number,
      'no_found_rows'       => true,
      'post_status'         => 'publish',
      'ignore_sticky_posts' => true,
    ), $instance ) );

    if ( ! $r->have_posts() ) {
      return;
    }
    ?>

      <div class="lpost">
        <div class="side-tit">
          <h6 class="ctit">
            <?php
              if ( $title ) {
                echo  $title;
              }
            ?>
          </h6>
        </div>
        <?php foreach ( $r->posts as $recent_post ) : ?>
          <?php
          $post_title = get_the_title( $recent_post->ID );
          $title      = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' );

          $em_post_thumb = get_the_post_thumbnail( $recent_post->ID );
          $em_thumbnail      = ( ! empty( $em_post_thumb ) ) ? $em_post_thumb : __( '(no title)' );
          ?>
        <div class="item">
          <a href="<?php the_permalink( $recent_post->ID ); ?>">
            <div class="sm-img">
              <?php echo $em_thumbnail ; ?>
            </div>
            <div class="info">
              <h5><?php echo $title ; ?></h5>
              <?php if ( $show_date ) : ?>
                <span><?php echo get_the_date( '', $recent_post->ID ); ?></span>
              <?php endif; ?>

            </div>
          </a>
        </div>    
        <?php endforeach; ?>                
      </div>

    <?php
    echo $args['after_widget'];
  }

}
function emotahar_recent_post_widgets() {
  register_widget( 'em_Widget_Recent_Posts' );
}
add_action( 'widgets_init', 'emotahar_recent_post_widgets' );

This will show on your widget like this :

custom widget

Add your CSS for your own styling.

I added my styling.

custom widget

That’s it. You have created a custom widget in WordPress Thank you.

Leave a comment

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