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
檢視更多 >