如何在WordPress中创建自定义小工具?
讲解如何使用WordPress代码创建自定义侧边栏小工具的方法。
-
玖比肆 评论在WordPress中创建自定义小工具非常简单。只需要遵循以下步骤:
1. 在您的主题文件夹中创建一个新文件夹,例如“custom-widgets”。
2. 在该目录下创建一个名为“custom-widget.php”的PHP文件,该文件将包含您的自定义侧边栏小工具代码。
3. 在custom-widget.php文件中,使用以下代码创建类及其属性。
```php
class Custom_Widget extends WP_Widget {function __construct() {
parent::__construct(
'custom_widget', // Widget ID
esc_html__( 'Custom Widget', 'text_domain' ), // Widget name
array( 'description' => esc_html__( 'A custom widget', 'text_domain' ), ) // Widget description
);
}
public function widget( $args, $instance ) {
// 输出小工具前端HTML
}public function form( $instance ) {
//输出小工具后端表单HTML
}public function update( $new_instance, $old_instance ) {
// 更新小工具实例设置
}}
```4. 在构造函数中定义小工具的名称,ID和说明。如果您需要配置选项,请使用form()方法输出后端表单元素。
5. 在widget()方法中编写要输出的HTML代码。$ args变量将包含侧边栏小工具的标题和外观。
6. 使用update方法更新小工具实例,使用新值覆盖旧值。
7. 在主函数文件中使用以下代码注册你的小工具。
```php
add_action( 'widgets_init', 'custom_widget_register' );function custom_widget_register() {
register_widget( 'Custom_Widget' );
}
```现在你已经注册了你的小工具,你可以将它添加到任何侧边栏上。
特别提示: 在添加到小工具到侧边栏之前, WordPress会调用form()方法来显示你添加表单内容的位置及样式。当然将你的HTML代码添加到widget()方法中,从而生成前端小工具输出,需要合理安排HTML元素类名及相应样式表。
2023年 5月 9日 上午3:33
