wp-includes/plugin.php:447Attach a callback to a WordPress action hook with add_action() so your function runs when core, a theme, or a plugin fires that event. Priority sets run order (lower runs first) and $accepted_args must match the number of parameters your callback takes; the function always returns true.
Adds a callback function to an action hook.
$hook_namestring$callbackcallable$priorityintoptional10$accepted_argsintoptional1trueEvery example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Hook a function onto init to register a custom post type when WordPress boots.
add_action( 'init', 'myplugin_register_book_type' );
function myplugin_register_book_type() {
register_post_type(
'book',
array(
'label' => 'Books',
'public' => true,
'supports' => array( 'title', 'editor', 'thumbnail' ),
)
);
}add_action() must run before the hook fires; a callback added after do_action( 'init' ) has already executed will never run.
Listen for save_post and take all three arguments the hook passes so you can tell inserts from updates.
add_action( 'save_post', 'myplugin_log_save', 10, 3 );
function myplugin_log_save( $post_id, $post, $update ) {
if ( wp_is_post_revision( $post_id ) ) {
return;
}
$verb = $update ? 'Updated' : 'Created';
error_log( sprintf( '%s post %d: %s', $verb, $post_id, $post->post_title ) );
}$accepted_args (here 3) must cover every required parameter your callback declares; with the default of 1, only $post_id is passed and PHP raises an ArgumentCountError.
function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) { return add_filter( $hook_name, $callback, $priority, $accepted_args );}Introduced in 1.2.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
src/wp-includes/plugin.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.