Wordpress自定义小工具(Widget)简单案例

发布时间 2023-05-21 14:20:29作者: 小易Smalle
  • 在主题对应目录创建文件如widgets.php
<?php

// 继承了 WP_Widget 这个类来创建新的小工具(Widget): 可在后台外观 - 小工具中添加此自定义小工具到页面具体位置
class my_widget extends WP_Widget {

    public function __construct()
	{
		// $widget_ops 可以给小工具进行描述等等。
		$widget_ops = array(
            'description' => '这是Widget的描述'
        );
		// $control_ops 可以对小工具进行简单的样式定义等等
		$control_ops = array('width' => 200, 'height' => 500);
		// $name 这个小工具的名称
		parent::__construct('my_widget', '一个简单的Widget', $widget_ops, $control_ops);
	}

	// 输出显示在页面上
	function widget($args, $instance) {
        // $instance 为当前小工具实例
		extract( $args );
		$title = apply_filters('widget_title', empty($instance['title']) ? __('如果title字段没有输入值,则这是默认的显示值') : $instance['title']);

		echo $before_widget;
		echo $before_title . $title . $after_title;
		echo $after_widget;
	}

	// 给小工具添加表单内容,用于在后台设置时进行内容输入
	function form($instance) {
        // 对输入值进行HTML转义,防止输入HTML格式内容
		$title = esc_attr($instance['title']);
        // 后面可直接写HTML代码,因此此处需要先结束PHP代码,之后再通过`<?php`重新开启PHP代码输出
		?>
		<p>
            <!-- esc_attr_e: 对值进行多语言翻译后再转义(wp内置了对`Title:`的翻译,即`标题:`,如果未找到翻译值则显示原始值) -->
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_attr_e('Title:'); ?>
                <!-- id: widget-my_widget-1-title, name: widget-my_widget[1][title] -->
                <input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
            </label>
        </p>
		<?php
	}

	// 更新保存
	function update($new_instance, $old_instance) {
		return $new_instance;
	}
}
register_widget('my_widget');
?>
  • functions.php中引入上述文件,如在末尾加上require_once get_template_directory() . '/widgets.php';
  • 使用:在后台外观 - 小工具中添加此自定义小工具到页面具体位置即可