WordPress学习——remove_action|详解|do_action|详解|add_action|详解

cera cera

remove_action() 是WordPress的核心函数,返回值为布尔值。主要用于移除一个附属于指定动作的钩子函数。并且你也可以用替代函数替换掉默认函数。remove_action()  的调用方法如下:

remove_action( string $tag, callable $function_to_remove, int $priority = 10 )

$tag:必填(字符串)。将要被删除的函数所连接到的动作 hook 。

$function_to_remove:必填(回调)。将要被移除的函数名称。

$priority:选填(整型)。函数最初挂载时的优先级。

该函数定义在 wp-includes/plugin.php 文件中:

function remove_action( $tag, $function_to_remove, $priority = 10 ) {
    return remove_filter( $tag, $function_to_remove, $priority );
}

参考文档:https://developer.wordpress.org/reference/functions/remove_action/

do_action() 是WordPress的核心函数,该函数没有返回值。作用是创建一个钩子,在特定的地方执行插件或者主题开发者挂载的函数,一般存在于某个特殊的节点或者事件上。do_action() 的调用方法如下:

do_action( string $tag,  $arg = '' )

$tag:必填(字符串)。将要被指向动作的函数名称。

$arg:选填(混合型)。传递给钩子函数的其他参数。 默认为空。

该函数定义在 wp-includes/plugin.php 文件中:

function do_action($tag, $arg = '') {
    global $wp_filter, $wp_actions, $wp_current_filter;

    if ( ! isset($wp_actions[$tag]) )
        $wp_actions[$tag] = 1;
    else
        ++$wp_actions[$tag];

    // Do 'all' actions first
    if ( isset($wp_filter['all']) ) {
        $wp_current_filter[] = $tag;
        $all_args = func_get_args();
        _wp_call_all_hook($all_args);
    }

    if ( !isset($wp_filter[$tag]) ) {
        if ( isset($wp_filter['all']) )
            array_pop($wp_current_filter);
        return;
    }

    if ( !isset($wp_filter['all']) )
        $wp_current_filter[] = $tag;

    $args = array();
    if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
        $args[] =& $arg[0];
    else
        $args[] = $arg;
    for ( $a = 2, $num = func_num_args(); $a < $num; $a++ )
        $args[] = func_get_arg($a);

    $wp_filter[ $tag ]->do_action( $args );

    array_pop($wp_current_filter);
}

参考文档:https://developer.wordpress.org/reference/functions/do_action/

add_action() 是 WordPress 核心代码执行期间或特定事件发生时启动的钩子函数。 插件可以指定使用 Action API 在这些特定点上执行其一个或多个PHP函数。简单来说就是通过 add_action() 将函数连接到指定 action 上。add_action() 的调用方法如下:

add_action( string $tag, callable $function_to_add, int $priority = 10,int $accepted_args = 1 )

$tag:必填(字符串)。$function_to_add 所挂载的动作(action)的名称。

$function_to_add:必填(回调)。你希望挂载的函数的名称。

$priority:可选(整型)。用于指定与特定的动作相关联的函数的执行顺序。数字越小,执行越早,默认值 10 。

$accepted_args:可选(整型)。挂钩函数所接受的参数数量。

该函数定义在 wp-includes/plugin.php 文件中:

function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
    return add_filter($tag, $function_to_add, $priority, $accepted_args);
}

通过源代码可知,其实际上还是调用了 add_filter() 函数,关于该函数请看这里>>> WordPress学习——add_filter()详解 。

参考文档:https://developer.wordpress.org/reference/functions/add_action/

cera cloudiplc tengxunyun

相关推荐

mjjping.com cera cera cloudiplc