wordpress使用do_action调用添加到hook的回调函数

更新时间:2022-06-15 21:35:10 来源:青锋建站 作者:青锋建站
  do_action可以执行add_action函数附加到action hook的回调函数。以下是青锋建站给大家分享的do_action函数的使用方法。

do_action

  ( string $hook_name, mixed $arg )调用已添加到action hook中的回调函数。

do_action函数简介

  此函数调用附加到动作钩子$hook_name的所有函数。通过简单地调用此函数,也可以创建新的动作钩子,使用$hook_name参数指定新钩子的名称。您可以向钩子传递额外的参数,就像使用apply_filper()一样。

do_action函数使用举例

  // The action callback function.
function example_callback( $arg1, $arg2 ) {
    // (maybe) do something with the args.
}
add_action( 'example_action', 'example_callback', 10, 2 );
/*
* Trigger the actions by calling the 'example_callback()' function
* that's hooked onto `example_action` above.
*
* - 'example_action' is the action hook.
* - $arg1 and $arg2 are the additional arguments passed to the callback.
$value = do_action( 'example_action', $arg1, $arg2 );

do_action函数参数

  $hook_name(string) (Required) 将要执行的action名称。
$arg(mixed) (Optional) 传递给附加到该action的函数的附加参数,默认为空。

do_action源代码

文件:wp-includes/plugin.php
function do_action( $hook_name, ...$arg ) {
    global $wp_filter, $wp_actions, $wp_current_filter;
    if ( ! isset( $wp_actions[ $hook_name ] ) ) {
        $wp_actions[ $hook_name ] = 1;
    } else {
        ++$wp_actions[ $hook_name ];
    }
    // Do 'all' actions first.
    if ( isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $hook_name;
        $all_args            = func_get_args(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
        _wp_call_all_hook( $all_args );
    }
    if ( ! isset( $wp_filter[ $hook_name ] ) ) {
        if ( isset( $wp_filter['all'] ) ) {
            array_pop( $wp_current_filter );
        }
        return;
    }
    if ( ! isset( $wp_filter['all'] ) ) {
        $wp_current_filter[] = $hook_name;
    }
    if ( empty( $arg ) ) {
        $arg[] = '';
    } elseif ( is_array( $arg[0] ) && 1 === count( $arg[0] ) && isset( $arg[0][0] ) && is_object( $arg[0][0] ) ) {
        // Backward compatibility for PHP4-style passing of `array( &$this )` as action `$arg`.
        $arg[0] = $arg[0][0];
    }
    $wp_filter[ $hook_name ]->do_action( $arg );
    array_pop( $wp_current_filter );
}
  以上就是青锋建站给大家分享的wordpress使用do_action调用添加到hook的回调函数,青锋建站承接网站建设服务,包括织梦建站,phpcms建站,wordpress建站,CMS系统开发,SEO网站优化,网络营销推广,企业邮箱,400电话。

转载请注明来源网址:青锋建站-http://www.sjzphp.com/cmsxitong/wordpressxt/do_action_1391.html

地方分站

电话 15632335515 | 邮箱 943703539@qq.com | QQ 943703539 | 微信 qingfengjianzhan

Copyright © 2016-2026 青锋建站 版权所有