编写和注册你的WordPress widget

King| 2015-03-05 未分类, WordPress, 教程 评论数( 0 )

这一部分是该系列教程的第二部分。在第一部分中,你已经了解了Widget  API和WP_Widget类。在这一部分我们将给您介绍通过创建类来创建并注册你的widget的过程的开始。

按照本教程的步骤,首先你需要以下准备:

  •  安装一个WordPress开发环境
  •  一个代码编辑器

这些准备工作完成后,创建的具体步骤如下:

安装插件

首先在目录wp-content/plugins下创建一个新的PHP文件,这里命名为tutsplus-list-subpages-widget.php。

接下来将以下代码加入到上述PHP文件中并保存。

提示:可以对上述代码的作者和URI进行修改。

<?php /*Plugin Name: List Subpages Widget Description: This widget checks if the current page has parent or child pages and if so, outputs a list of the highest ancestor page and its descendants. This file supports part 1 of the series to create the widget and doesn't give you a functioning widget. Version: 0.1 Author: Rachel McCollin Author URI: http://rachelmccollin.com

创建widget类

第二步就是创建一个新类来扩展WP_Widget类。具体步骤很简单,把以下代码加入到你的插件文件中并保存:

<?phpclass Tutsplus_List_Pages_Widget extends WP_Widget {function __construct() { } function form( $instance ) { } function update( $new_instance, $old_instance ) { } function widget( $args, $instance ) { } }?>

这个新类中主要包括:

  •  __construct 会构造一个函数。在这个函数里面你可以做出一些定义,比如WordPress widget的ID、标题还有说明。
  • form函数会在WordPress widget界面创建表单,让用户来自定义或者激活widget。
  • update函数确保WordPress能及时更新用户在WordPress widget界面输入的任何设置。
  • widget函数定义了在网站前端通过WordPress widget输出的内容。

注册widget

只有对WordPress进行了注册,你的WordPress widget才能工作。我们需要做的就是在新建的类下添加以下函数和钩子: <?php function tutsplus_register_list_pages_widget() { register_widget( 'Tutsplus_List_Pages_Widget' ); } add_action( 'widgets_init', 'tutsplus_register_list_pages_widget' ); ?>

上述代码中,register_widget()函数是一个WordPress函数,add_action()函数的功能是将你创建的函数挂入widget_init钩子,确保该函数可以被WordPress拾起。 注意:现在你的WordPress widget还无法工作,也不会再widget界面中显示。想要自己的widget正常工作必须完成本系列教程的所有步骤。

小结

现在你已经开始创建你的WordPress widget了。你已经为widget创建了插件,并且为构造widget和注册widget创建了类。下一篇教程将给大家介绍如何用__construct函数构造widget。

聚焦云计算,扫描二维码,关注HostUCan云计算

有好的文章希望站长之间帮助分享推广,猛戳这里我要投稿

您需要登录后才可以评论登录|注冊

暂无评论