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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
<?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' ); } ?> <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; } }
    New question is currently disabled!