Actions: perform tasks.
Filters: modify data before output.
1. add_action()
Purpose: Attach a function to a specific action hook so it runs at that point.
Syntax:
add_action( 'hook_name', 'your_function', $priority, $accepted_args );
hook_name→ The action hook you want to attach toyour_function→ The callback functionpriority→ Optional, default10(lower number runs first)accepted_args→ Optional, number of arguments passed
Example:
// Add a message to the footer
add_action('wp_footer', 'my_footer_message');
function my_footer_message() {
echo '<p>Thank you for visiting!</p>';
}
2. remove_action()
Purpose: Detach a function from an action hook. Useful if a plugin or theme added something you don’t want.
Syntax:
remove_action( 'hook_name', 'your_function', $priority );
Example:
// Remove a default WordPress emoji script from the head
remove_action('wp_head', 'print_emoji_detection_script', 7);
⚠️ Important: The priority must match the original
add_actioncall.
3. add_filter()
Purpose: Attach a function to a filter hook to modify data. Must return a value.
Syntax:
add_filter( 'hook_name', 'your_function', $priority, $accepted_args );
Example:
// Add text at the end of all post content
add_filter('the_content', 'my_custom_content');
function my_custom_content($content) {
$content .= '<p>Thank you for reading!</p>';
return $content; // Must return the modified content
}
4. do_action()
Purpose: Execute all functions attached to an action hook. Usually used by WordPress core or your theme/plugin to define a hook.
Syntax:
do_action( 'hook_name', $arg1, $arg2, ... );
Example:
// In a theme file
do_action('before_main_content');
// Functions hooked to 'before_main_content' will execute
add_action('before_main_content', 'my_custom_message');
function my_custom_message() {
echo '<h2>Welcome to my site!</h2>';
}
Essentially,
do_action()is where the hook is triggered, andadd_action()is where you attach your function to it.
Quick Summary Table
| Function | Purpose | Returns |
|---|---|---|
add_action() | Attach a function to an action hook | Nothing |
remove_action() | Remove a function from an action hook | Nothing |
add_filter() | Attach a function to a filter hook | Nothing |
do_action() | Execute all functions attached to an action | Nothing |
