This page redirects to an external site: https://developer.wordpress.org/reference/functions/add_action/
Languages: English • 日本語 中文(简体) • 한국어 • (Add your language)
Hooks a function on to a specific action.
More specifically, this function will run the function $function_to_add when the event $hook occurs.
This function is an alias to add_filter().
See Plugin API/Action Reference for a list of action hooks. Actions are (usually) triggered when the WordPress core calls do_action().
<?php add_action( $hook, $function_to_add, $priority, $accepted_args ); ?>
To email some friends whenever an entry is posted on your blog:
function email_friends( $post_ID ) {
$friends = '[email protected], [email protected]';
wp_mail( $friends, "sally's blog updated", 'I just put something on my blog: http://blog.example.com' );
return $post_ID;
}
add_action( 'publish_post', 'email_friends' );
A hooked function can optionally accept arguments from the action call, if any are set to be passed. In this simplistic example, the echo_comment_id function takes the $comment_id argument, which is automatically passed to when the do_action() call using the comment_id_not_found filter hook is run.
function echo_comment_id( $comment_id ) {
echo 'Comment ID ' . $comment_id . ' could not be found';
}
add_action( 'comment_id_not_found', 'echo_comment_id', 10, 1 );
To use add_action() when your plugin or theme is built using classes, you need to use the array callable syntax. You would pass the function to add_action() as an array, with your object as the first element, then the name of the class method, like so:
class My_Plugin_Class {
public function save_posts_hook() {
// do stuff here...
}
}
$my_class = new My_Plugin_Class;
add_action( 'save_post', array( $my_class, 'save_posts_hook' ) );
If the class method can be called statically, the approach is much like the way you would a function: you can just pass a string with the full method:
class My_Plugin_Class {
public static function save_posts_hook() {
// do stuff here...
}
}
add_action( 'save_post', 'My_Plugin_Class::save_posts_hook' );
To find out the number and name of arguments for an action, simply search the code base for the matching do_action() call. For example, if you are hooking into 'save_post', you would find it in post.php:
<?php do_action( 'save_post', $post_ID, $post, $update ); ?>
Your add_action call would look like:
<?php add_action( 'save_post', 'my_save_post', 10, 3 ); ?>
And your function would be:
function my_save_post( $post_ID, $post, $update ) {
// do stuff here
}
Since 1.2.0
add_action() is located in wp-includes/plugin.php.