WordPress添加动作函数:add_action

2020年5月12日 飞飞 阅读(1.2K)
知识付费主题,优惠促销中:xx-blog主题

说明

函数连接到指定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: https://www.xxzhuti.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 找到:

<?php do_action( 'save_post', $post_ID, $post ); ?>

你的 add_action 调用将是这样:

<?php add_action( 'save_post', 'my_save_post', 10, 2 ); ?>

而且你的函数将是这样:

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...
}
}

源文件

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


关注微信公众号『xx主题网

第一时间了解最新网络动态
关注博主不迷路~

未经允许不得转载:xx主题网 » WordPress添加动作函数:add_action
分享到:

评论抢沙发

要发表评论,您必须先

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

扫码关注微信公众号

扫描关注xx主题网