do_action

函数
do_action ( $hook_name, $arg )
参数
  • (string) $hook_name The name of the action to be executed.
    Required:
  • (mixed) $arg Optional. Additional arguments which are passed on to the functions hooked to the action. Default empty.
    Required:
定义位置
相关方法
doing_actiondid_actionadd_actionhas_actiondo_favicon
引入
1.2.0
弃用
-

do_action: 这个函数用来执行一个动作钩子。它接受一个钩子名称和一个可选的参数列表来传递给钩子。

调用已添加到动作钩子的回调函数。

这个函数调用所有附属于动作钩子`$hook_name`的函数。可以通过简单地调用这个函数来创建新的动作钩子,用`$hook_name`参数指定新钩子的名称。

你可以给钩子传递额外的参数,就像你可以用`apply_filters()`一样。

使用实例:

// 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.
do_action( ‘example_action’, $arg1, $arg2 );

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 );
}

常见问题

FAQs
查看更多 >