add_action()

最后更新于:2021-11-25 19:08:13

add_action( string$hook_name, callable$callback, int$priority=10, int$accepted_args=1)

Adds a callback function to an action hook.

参数

$hook_name

(string) (Required) The name of the action to add the callback to.

$callback

(callable) (Required) The callback to be run when the action is called.

$priority

(int) (Optional) Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.

Default value: 10

$accepted_args

(int) (Optional) The number of arguments the function accepts.

Default value: 1

响应

(true) Always returns true.

源文件

文件: gc-includes/plugin.php

function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
	return add_filter( $hook_name, $callback, $priority, $accepted_args );
}
/**
 * Class GC_Docs_Class.
 */
class GC_Docs_Class {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'save_post', array( $this, 'gcdocs_save_posts' ) );
	}

	/**
	 * Handle saving post data.
	 */
	public function gcdocs_save_posts() {
		// do stuff here...
	}
}

$gcdocsclass = new GC_Docs_Class();
/**
 * Class GC_Docs_Static_Class.
 */
class GC_Docs_Static_Class {

	/**
	 * Initializer for setting up action handler
	 */
	public static function init() {
		add_action( 'save_post', array( get_called_class(), 'gcdocs_save_posts' ) );
	}

	/**
	 * Handler for saving post data.
	 */
	public static function gcdocs_save_posts() {
		// do stuff here...
	}
}

GC_Docs_Static_Class::init();
/**
 * Send email to my friends.
 *
 * @param int $post_id Post ID.
 * @return int Post ID.
 */
function gcdocs_email_friends( $post_id ) {
	$friends = 'bob@example.org, susie@example.org';
	gc_mail( $friends, "sally's blog updated", 'I just put something on my blog: http://blog.example.com' );

	return $post_id;
}
add_action( 'publish_post', 'gcdocs_email_friends' );

public function __construct() {
    // Actions
    add_action('init', array($this, 'call_somefunction'));
}

/**
 *    Intermediate function to call add_action with parameters
 */
public function call_somefunction() {
    $this->somefunction('Hello World');
}

/**
 *    Actual function that does something
 */
public function somefunction($text) {
    echo $text;
}