wordpress自定义小工具(widget)详解

class My_Widget extends WP_Widget { //继承了 WP_Widget 这个类来创建新的小工具(Widget)
	function My_Widget() {
		// 主要内容方法
	}

	function form($instance) {
		 // 给小工具(widget) 添加表单内容
	}

	function update($new_instance, $old_instance) {
		 // 进行更新保存
	}

	function widget($args, $instance) {
		// 输出显示在页面上
	}

}
register_widget('My_Widget');

我们可以使用上面的这个代码结构来写一个小例子。代码是这样的:

<?php 

class My_Widget extends WP_Widget {

	function My_Widget()
	{
		$widget_ops = array('description' => '一个简单的小测试');
		$control_ops = array('width' => 400, 'height' => 300);
		parent::WP_Widget(false,$name='一个简单的Widget',$widget_ops,$control_ops);  

                //parent::直接使用父类中的方法
                //$name 这个小工具的名称,
                //$widget_ops 可以给小工具进行描述等等。
                //$control_ops 可以对小工具进行简单的样式定义等等。
	}

	function form($instance) { // 给小工具(widget) 添加表单内容
		$title = esc_attr($instance['title']);
	?>
	<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_attr_e('Title:'); ?> <input class="widefat" 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;
	}
	function widget($args, $instance) { // 输出显示在页面上
	extract( $args );
        $title = apply_filters('widget_title', empty($instance['title']) ? __('小测试') : $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php if ( $title )
                        echo $before_title . $title . $after_title; ?>
              <?php echo $after_widget; ?>

        <?php
	}
}
register_widget('My_Widget');
?>

ps: 可以在模板目录下新建一个文件如 widget.php  把上边小工具代码 放入widget.php ,然后把widget.php 文件包含到 functions.php 即可使代码更清晰。包含代码如下:

require_once( dirname(__FILE__) . '/widgets.php' );
原文地址:http://www.favortt.com/wordpress-widget-jiangjie-2.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值