php add action,WordPress函数:add_action(添加动作)

本文详细介绍了如何在WordPress中使用add_action函数将函数与特定动作关联,以便在特定事件发生时执行定制操作。通过实例演示了如何在发布新内容时发送邮件通知,以及如何接收并处理评论ID找不到的情况。
摘要由CSDN通过智能技术生成

说明

将函数连接到指定action(动作)。

用法

add_action( $tag, $function_to_add, $priority,

$accepted_args );

?>

参数

$tag

(字符串)(必填)$function_to_add  所挂载的动作(action)的名称。(在Plugin API/Action Reference 上查看动作hook列表)。也可以是一个主题或插件文件内部的一个动作,或者特定的标签“all”,这个函数将被所有的钩子(hooks)调用。

默认值:None

$function_to_add

(回调)(必填)你希望挂载的函数的名称。注:在 PHP“回调”类型文档中 所罗列的字符串格式化的语法均可用。

默认值:None

$priority

(整数)(可选)用于指定与特定的动作相关联的函数的执行顺序。数字越小,执行越早,具有相同优先级的函数在它们被添加到动作的顺序执行。

默认值:10

$accepted_args

(整数)(可选)挂钩函数所接受的参数数量。在 WordPress1.5.1 及以后的版本中,挂钩函数可以是调用do_action() 或 apply_filters()时设置的参数。例如,comment_id_not_found动作将传递任何函数,若该函数将所请求的评论编号连接到该动作。

默认值:1

返回值

(布尔)总是True。

示例

简单的挂钩

博客发表新内容时用电子邮件通知朋友:

function email_friends( $post_ID )

{

$friends = ‘bob@example.org, susie@example.org’;

wp_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’ );

接受的参数

挂钩函数可以选择接受从动作调用的参数,如果有任何要传递的话。在这个简单的例子中,echo_comment_id  函数需要 $comment_id 参数,该参数将在 comment_id_not_found 过滤钩子运行时通过 do_action() 传递。

function echo_comment_id( $comment_id )

{

echo ‘Comment ID ‘ . $comment_id . ‘ could not be found’;

}

add_action( ‘comment_id_not_found’, ‘echo_comment_id’, 10, 1 );

注释

要找出一个动作的参数的ID和名称,只需搜索匹配 do_action() 调用的代码库。举例来说,如果你挂载到’save_post’,你会在 post.php 找到:

你的 add_action 调用将是这样:

而且你的函数将是这样:

function my_save_post( $post_ID, $post )

{

// do stuff here

}

在一个类中使用 add_action

当你的插件或主题使用类来创建时,使用 add_action 钩子,在类中添加 $this 和 函数名称 到你的 add_action 回调,像这样:

class MyPluginClass

{

public function __construct()

{

//add your actions to the constructor!

add_action( ‘save_post’, array( $this, ‘myplugin_save_posts’ ) );

}

public function myplugin_save_posts()

{

//do stuff here…

}

}

函数历史

始见于 WordPress 1.2.0

源文件

add_action() 位于 wp-includes/plugin.php

原文:http://codex.wordpress.org/Function_Reference/add_action

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值