这是一段有详细注释的WordPress自定义小工具(Widget )开发实例代码,可用于制作主题时集成自定义小工具,将代码添加到主题functions.php中,具体效果如图:
- <?php
- add_action( \’widgets_init\’, \’example_load_widgets\’ );
- example_load_widgets() {
- register_widget( \’Example_Widget\’ );
- }
- Example_Widget WP_Widget {
- Example_Widget() {
- = ( \’classname\’ => \’example\’, \’description\’ => __(\’An example widget that displays a person\\\’s name sex.\’, \’example\’) );
- = ( \’width\’ => 300, \’height\’ => 350, \’id_base\’ => \’example-widget\’ );
- ->WP_Widget( \’example-widget\’, __(\’Example Widget\’, \’example\’), , );
- }
- widget( , ) {
- extract( );
- = apply_filters(\’widget_title\’, [\’title\’] );
- = [\’name\’];
- = [\’sex\’];
- = isset( [\’show_sex\’] ) ? [\’show_sex\’] : false;
- ;
- ( )
- . . ;
- ( )
- printf( \'<p>\’ . __(\’Hello. My name is %1.\’, \’example\’) . \'</p>\’, );
- ( )
- printf( \'<p>\’ . __(\’I am a %1.\’, \’example.\’) . \'</p>\’, );
- ;
- }
- update( , ) {
- = ;
- [\’title\’] = ( [\’title\’] );
- [\’name\’] = ( [\’name\’] );
- [\’sex\’] = [\’sex\’];
- [\’show_sex\’] = [\’show_sex\’];
- ;
- }
- form( ) {
- = ( \’title\’ => __(\’Example\’, \’example\’), \’name\’ => __(\’John Doe\’, \’example\’), \’sex\’ => \’male\’, \’show_sex\’ => true );
- = wp_parse_args( () , ); ?>
- <!– Widget Title: Text Input –>
- <p>
- <label =><?php _e(\’Title:\’, \’hybrid\’); ?></label>
- <input id= name= value= style= />
- </p>
- <!– Your Name: Text Input –>
- <p>
- <label =><?php _e(\’Your Name:\’, \’example\’); ?></label>
- <input id= name= value= style= />
- </p>
- <!– Sex: Select Box –>
- <p>
- <label =><?php _e(\’Sex:\’, \’example\’); ?></label>
- <select id= name= = style=>
- <option <?php ( \’male\’ == [\’format\’] ) \’selected=\’; ?>>male</option>
- <option <?php ( \’female\’ == [\’format\’] ) \’selected=\’; ?>>female</option>
- </select>
- </p>
- <!– Show Sex? Checkbox –>
- <p>
- <input = type= <?php checked( [\’show_sex\’], true ); ?> id= name= />
- <label =><?php _e(\’Display sex publicly?\’, \’example\’); ?></label>
- </p>
- <?php
- }
- }
- ?>
原文:http://justintadlock.com/
暂无评论内容