WordPress还允许开发人员创建自己的自定义小部件。许多WordPress主题和插件都带有自己的自定义小部件,您可以将其添加到侧边栏。
例如,您可以在不编写任何代码的情况下将联系表单,做网站简单吗,自定义登录表单或照片库添加到侧边栏。
话虽如此,让我们看看如何在WordPress中轻松创建自己的自定义小部件。
|
1
2
3
4
五
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
三十
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
58
59
60
61
62 |
// Register and load the widgetfunction wpb_load_widget() { register_widget( 'wpb_widget' );}add_action( 'widgets_init', 'wpb_load_widget' );// Creating the widget class wpb_widget extends WP_Widget {function __construct() {parent::__construct(// Base ID of your widget'wpb_widget', // Widget name will appear in UI__('WPBeginner Widget', 'wpb_widget_domain'), // Widget descriptionarray( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), ) );}// Creating widget front-endpublic function widget( $args, $instance ) {$title = apply_filters( 'widget_title', $instance['title'] );// before and after widget arguments are defined by themesecho $args['before_widget'];if ( ! empty( $title ) )echo $args['before_title'] . $title . $args['after_title'];// This is where you run the code and display the outputecho __( 'Hello, World!', 'wpb_widget_domain' );echo $args['after_widget'];} // Widget Backend public function form( $instance ) {if ( isset( $instance[ 'title' ] ) ) {$title = $instance[ 'title' ];}else {$title = __( 'New title', 'wpb_widget_domain' );}// Widget admin form?><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 } // Updating widget replacing old instances with newpublic function update( $new_instance, $old_instance ) {$instance = array();$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';return $instance;}} // Class wpb_widget ends here |
现在您可以访问您的网站以查看它的实际效果,做网站简单吗。
现在让我们再次研究代码。
做网站简单吗,首先,我们注册了’wpb_widget’并加载了我们的自定义小部件。之后我们定义了该小部件的功能,以及如何显示小部件后端。
wpb_text_domain什么?
WordPress使用gettext来处理翻译和本地化。这wpb_text_domain并__e 告诉gettext使字符串可用于翻译。了解如何找到准备好翻译的WordPress主题。
如果要为主题创建自定义窗口小部件,则可以wpb_text_domain使用主题的文本域进行替换。
我们希望本文能帮助您学习如何轻松创建自定义WordPress小部件。您可能还希望查看我们的网站最有用的WordPress小部件列表。