加载中……
之前开发Follow5和天气预报的WordPress插件,都是用了WordPress的WP_Widget函数开发的WordPress侧边栏挂件插件。今天就说说WordPress2.8+的版本使用WP_Widget函数轻松开发widget的方法。
WP_Widget函数的默认用法是这样子的:
class My_Widget extends WP_Widget { function My_Widget() { // 挂件实例化 } function widget($args, $instance) { // 输出挂件内容 } function update($new_instance, $old_instance) { // 选项保存过程 } function form($instance) { // 在管理界面输出选项表单 } } register_widget('My_Widget');
简单分析一下:
My_Widget :可以是任意的你喜欢的名字,是你开发插件的构造函数
widget:跟下面的update,form都是WordPress默认的名字,不得改变。widget为在页面侧边栏输出的挂件内容
update:选项更新时候保存处理的函数
form:在后台管理界面显示的输出选项表单
下面我分析一下我的天气预报插件的源代码,解释一下WP_Widget的用法,源代码如下所示:
<?php class Weather_Widget extends WP_Widget { /** 构造函数 */ function Weather_Widget() { $widget_ops = array( 'description' => '设置您的<strong>来访者天气</strong> Widget,拖动到右侧侧边栏即可使用' ); parent::WP_Widget('Weather', $name = 'Weather Widget',$widget_ops); } function widget($args, $instance) { extract($args); $my_Weather_content = '<div id="myTQ"><div id="weatherLoad"><img src="'.get_bloginfo('url').'/wp-content/plugins/weather/images/loading.gif" /><br/><span>天气加载中……</span></div></div>'; echo $before_widget.$before_title.$instance['title'].$after_title.$my_Weather_content.$after_widget; } function update($new_instance, $old_instance) { return $new_instance; } function form($instance) { $title = esc_attr($instance['title']); ?> <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _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 } } add_action('widgets_init', create_function('', 'return register_widget("Weather_Widget");'));
构造函数Weather_Widget
作用是构造函数,添加后台显示信息。
两个数组:
$widget_ops,用来保存类名和描述,以便在控制面板正确显示工具信息
$control_ops 是可选参数,用来定义小工具在控制面板显示的宽度和高度(可选,天气预报插件未使用本数组)
最后一步代码:
parent::WP_Widget('Weather', $name = 'Weather Widget',$widget_ops);
调用WP_Widget来初始化我们的小工具,其中name为插件在后台显示的名称。
效果截图:
前端显示函数widget
首先使用了extract函数把数组中的keys转换成变量,比如下面用到的$before_widget、$before_title、$after_title、$after_widget,这些变量不同的主题模块有不同的值。
然后我们使用echo来显示到页面上来
更新处理函数update
update函数用于更新保存的设置。其实这个函数可以不定义,不过为了提高安全性,我们一般用此函数进行字符串的过滤。如下面的代码:
$instance = $old_instance; $instance['title'] = strip_tags(stripslashes($new_instance['title'])); return $instance;
可以过滤掉不安全的title字符
选项设置表单函数form
form函数一般是用来显示小工具的选项设置表单,表单的内容根据需要自己定义。天气预报插件小工具可以让用户自定义1个内容:title插件名称。
$instance数组的key:title是可以自己定义的,但在前后的使用过程中要保持一致。另外wordpress提供了两函数get_field_name 和get_field_id来保证表单内每一项设置都保存到相应的数组Key中。
效果截图:
注册小工具,使之激活
最后使用WordPress内置的add_action函数激活天气预报插件就可以了~
注意:注册工具的代码要添加到上面的类定义之外!
最终来访者天气预报插件的效果图:

有关该来访者天气预报插件的源代码下载以及安装和使用方法,可以参看:
http://www.js8.in/wordpress-weather



你的部落格很不错啊,感觉我们有共同的爱好呢
@admin 已经链接了,只不过暂时还不在首页,等我首页的链接设计好了之后把你的站点加上去
今天是圣诞节啊,祝大家节日快乐。呵呵
呵呵~是吗~那就加链接哦~
嗯~谢谢啦~啊哈哈