Simple WordPress Widget Template
Widgets are utilized by tons of WordPress themes and plugins as a way to display customized content in various locations, and they’re relatively easy to create, as long as you have the appropriate resources. The code below will give you everything you need to make extensive and advanced widgets that can do anything you want.
I am not going to explain what everything does, but it is not difficult to figure out. You can copy the code below into your functions.php or plugin file; it will register a simple widget that accepts a “title” and “message” options.
|
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 51 52 53 54 55 56 57 |
<?php /** * Example Widget Class */ class example_widget extends WP_Widget { /** constructor -- name this the same as the class above */ function example_widget() { parent::WP_Widget(false, $name = 'Example Text Widget'); } /** @see WP_Widget::widget -- do not rename this */ function widget($args, $instance) { extract( $args ); $title = apply_filters('widget_title', $instance['title']); $message = $instance['message']; ?> <?php echo $before_widget; ?> <?php if ( $title ) echo $before_title . $title . $after_title; ?> <ul> <li><?php echo $message; ?></li> </ul> <?php echo $after_widget; ?> <?php } /** @see WP_Widget::update -- do not rename this */ function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['message'] = strip_tags($new_instance['message']); return $instance; } /** @see WP_Widget::form -- do not rename this */ function form($instance) { $title = esc_attr($instance['title']); $message = esc_attr($instance['message']); ?> <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('message'); ?>"><?php _e('Simple Message'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('message'); ?>" name="<?php echo $this->get_field_name('message'); ?>" type="text" value="<?php echo $message; ?>" /> </p> <?php } } // end class example_widget add_action('widgets_init', create_function('', 'return register_widget("example_widget");')); ?> |
To expand on this simple widget, just duplicate and rename the fields, then modify their field types as necessary.
I will explain this code in detail, and provide examples of more advanced widgets in upcoming posts.
