In WordPress, add_action() says: “When this event happens, run my function.” The event is called a hook, and a hook that lets you do something is called an action.
WordPress marks many moments in a page request, such as loading styles, printing the head, or saving a post. At each moment it calls do_action(). Your function runs only when that happens. A function you add with add_action() is called a callback, and its return value is ignored.
Syntax
Give it the hook name and the name of your function.
WordPress
<?php add_action( 'init', 'my_function' ); ?>
Call
What it does
add_action( 'wp_enqueue_scripts', 'my_styles' )
Run my_styles() when WordPress loads CSS and JavaScript.
add_action( 'wp_head', 'my_meta', 5 )
Run my_meta() early, because 5 is lower than the default 10.
add_action( 'save_post', 'my_save', 10, 3 )
Let my_save() receive 3 values from the hook.
Put add_action() in functions.php or a plugin file, so it runs before the hook fires.
Full declaration
WordPress
add_action( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 ): true
Parameters
Parameter
Description
$hook_name
string. The name of the action hook, for example init, wp_head, or wp_enqueue_scripts.
$callback
callable. The function to run. Usually the name of a function as a string, such as 'my_function'.
$priority
int. Order of running. Lower numbers run earlier. Default is 10. Callbacks with the same priority run in the order you added them.
$accepted_args
int. How many values from the hook your function can receive. Default is 1.
Return Value
Return Value
Description
true
Always returns true. You do not need to check it.
WordPress Examples
Three short examples. Each one shows the code and what it prints or does.
Example 1 — Load a stylesheet
The most common use. Add your CSS file when WordPress prepares the page.