工作中用到了wordpress mu,由于满足不了客户要求,只能在基础上稍微改造,期间发现wordpress团队太牛了!下面将这段时间用的最普遍的Actions做个小结:
Action(动作)在WordPress进行某些特殊事件处理时被触发,例如发布日志,修改主题,或者在管理员面板显示页面。你的插件可以通过执行PHP函数来发挥作用,他们可以用来做如下事情:
- 修改数据库中的数据
- 发送Email消息
- 修改在浏览器中显示的信息(包括管理员看到的和访问者看到的)
- 等等 太多的事情都可以通过Actions在不修改源码的基础上完成
- add_action();
将函数连接到指定action(动作)。在Plugin API/Action Reference 上查看动作hook列表。wordpress核心调用do_action() 时触发动作。
- /*
- $tag WordPress代码中要加入函数的位置标签;(字符串)希望连接到的动作名称(在Plugin API/Action Reference 上查看动作hook列表)
- $function_to_add:是要加入的函数;(回调)希望调用的函数名称。注意: the PHP documentation for the 'callback' type中解释的语法均可用。
- $priority:函数调用的优先级;函数的重要程度。改变此参数以决定函数与其他函数的调用顺序。默认值为10,因此(例如)将值设为5时函数运行较早,设为12时运行则较晚。
- $accepted_args:要接受的参数。函数所接受参数的数量。在WordPress 1.5.1及之后版本中,连接的函数可吸收其它在调用do_action() 或 apply_filters()时设置的参数。例如,comment_id_not_found动作将传递任何函数,若该函数将所请求的评论编号连接到该动作。
- */
- add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1);
- /*
- 示例
- 博客发表新内容时用电子邮件通知朋友:
- */
- add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1);
- function email_friends($post_ID) {
- $friends = 'bob@example.org, susie@example.org';
- mail($friends, "sally's blog updated" , 'I just put something on my blog:http://blog.example.com');
- return $post_ID;
- }
- add_action('publish_post', 'email_friends');
上面是官方举例,开发中我用到Action的时候是这么做的,记录一下:
当注册时候,如果注册成功,我想在数据库里加一个字段 来表示是企业用户还是个人用户(typeid 默认0 个人用户 1企业用户)
- add_action('update_signup_type','tw_update_signup_typeid',10,3);
- /*
- * 更新blog的typieid (0 个人用户 1 企业用户)
- */
- function tw_update_signup_typeid($user_name,$user_email,$typeid){
- global $wpdb;
- if($typeid == 1){//因为默认已经为0了
- $wpdb->update( $wpdb->signups, array('typeid' => $typeid), array('user_login' => $user_name,'user_email' =>$user_email ) );
- }
- return;
- }
- do_action('update_signup_type', $user_name,$user_email,$typeid);
- do_action()
- /*
- $tag (string) (required) The name of the hook you wish to create.Default: None
- $arg (mixed) (optional) The list of arguments this hook accepts. Default: ''*/
- <?php do_action( $tag, $arg ); ?>