下面的代码是一个简易代码,直接放入function.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 |
function hstngr_register_widget() { register_widget( 'hstngr_widget' ); } add_action( 'widgets_init', 'hstngr_register_widget' ); class hstngr_widget extends WP_Widget { function __construct() { parent::__construct( // widget ID 'hstngr_widget', // widget name __('Hostinger Sample Widget', ' hstngr_widget_domain'), // widget description array( 'description' => __( 'Hostinger Widget Tutorial', 'hstngr_widget_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']; //output echo __( 'Greetings from Hostinger.com!', 'hstngr_widget_domain' ); echo $args['after_widget']; } public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) $title = $instance[ 'title' ]; else $title = __( 'Default Title', 'hstngr_widget_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; } } |