0
0
WordpressHow-ToBeginner · 4 min read

How to Use add_action in WordPress: Simple Guide

In WordPress, use add_action to connect your custom function to a specific event or hook. This lets your code run automatically when WordPress reaches that point, like loading the header or saving a post.
📐

Syntax

The add_action function connects your custom function to a WordPress hook. It has three main parts:

  • hook_name: The name of the WordPress event or hook to attach to.
  • your_function: The name of your custom function to run.
  • priority (optional): Order to run if many functions use the same hook (default is 10).
  • accepted_args (optional): Number of arguments the function accepts (default is 1).
php
add_action('hook_name', 'your_function', 10);
💻

Example

This example shows how to add a message to the WordPress footer using add_action. The custom function show_footer_message runs when the wp_footer hook triggers.

php
<?php
function show_footer_message() {
    echo '<p style="text-align:center; color:gray;">Thank you for visiting my site!</p>';
}
add_action('wp_footer', 'show_footer_message');
?>
Output
Displays a centered gray message 'Thank you for visiting my site!' at the bottom of every page in the footer area.
⚠️

Common Pitfalls

Common mistakes when using add_action include:

  • Using the wrong hook name or misspelling it, so your function never runs.
  • Not defining the function before calling add_action.
  • Forgetting to use quotes around function names or hook names.
  • Using a function that requires parameters without handling them properly.
php
<?php
// Wrong: function not defined before add_action
add_action('init', 'my_init_function');

// Correct:
function my_init_function() {
    // Your code here
}
add_action('init', 'my_init_function');
📊

Quick Reference

ParameterDescriptionDefault
hook_nameName of the WordPress hook to attach toRequired
your_functionName of your custom function to runRequired
priorityOrder to run functions on the same hook10
accepted_argsNumber of arguments your function accepts1

Key Takeaways

Use add_action to run your custom function at specific WordPress events or hooks.
Always define your function before calling add_action with its name.
Check hook names carefully to ensure your function runs at the right time.
Use the priority parameter to control the order if multiple functions use the same hook.
Remember to handle function arguments if the hook passes any.