do_action()

最后更新于:2021-11-26 02:54:22

do_action( string$hook_name, mixed$arg)

Calls the callback functions that have been added to an action hook.

参数

$hook_name

(string) (Required) The name of the action to be executed.

$arg

(mixed) (Optional) Additional arguments which are passed on to the functions hooked to the action. Default empty.

源文件

文件: gc-includes/plugin.php

function do_action( $hook_name, ...$arg ) {
	global $gc_filter, $gc_actions, $gc_current_filter;

	if ( ! isset( $gc_actions[ $hook_name ] ) ) {
		$gc_actions[ $hook_name ] = 1;
	} else {
		++$gc_actions[ $hook_name ];
	}

	// Do 'all' actions first.
	if ( isset( $gc_filter['all'] ) ) {
		$gc_current_filter[] = $hook_name;
		$all_args            = func_get_args(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
		_gc_call_all_hook( $all_args );
	}

	if ( ! isset( $gc_filter[ $hook_name ] ) ) {
		if ( isset( $gc_filter['all'] ) ) {
			array_pop( $gc_current_filter );
		}

		return;
	}

	if ( ! isset( $gc_filter['all'] ) ) {
		$gc_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];
	}

	$gc_filter[ $hook_name ]->do_action( $arg );

	array_pop( $gc_current_filter );
}
# ======= Somewhere in a (mu-)plugin, theme or the core ======= #

/**
 * You can have as many arguments as you want,
 * but your callback function and the add_action call need to agree in number of arguments.
 * Note: `add_action` above has 2 and 'i_am_hook' accepts 2. 
 * You will find action hooks like these in a lot of themes & plugins and in many place @core
 * @see: https://codex.gechiui.org/Plugin_API/Action_Reference
 */

# ======= e.g., inside your functions.php file ======= #

/**
 * Define callback function
 * Inside this function you can do whatever you can imagine
 * with the variables that are loaded in the do_action() call above.
 */
function gcdocs_who_is_hook( $a, $b ) {
	echo '<code>';
		print_r( $a ); // `print_r` the array data inside the 1st argument
	echo '</code>';

	echo '<br />'.$b; // echo linebreak and value of 2nd argument
}

// then add it to the action hook, matching the defined number (2) of arguments in do_action
// see [https://codex.gechiui.org/Function_Reference/add_action] in the Codex 

// add_action( $tag, $function_to_add, $priority, $accepted_args );
add_action( 'gcdocs_i_am_hook', 'gcdocs_who_is_hook', 10, 2 );

// Define the arguments for the action hook
$a = array(
	'eye patch'  => 'yes',
	'parrot'     => true,
	'wooden leg' => 1
);
$b = __( 'And Hook said: "I ate ice cream with Peter Pan."', 'textdomain' ); 

// Executes the action hook named 'i_am_hook'
do_action( 'gcdocs_i_am_hook', $a, $b );