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
| Parameter | Description | Default |
|---|---|---|
| hook_name | Name of the WordPress hook to attach to | Required |
| your_function | Name of your custom function to run | Required |
| priority | Order to run functions on the same hook | 10 |
| accepted_args | Number of arguments your function accepts | 1 |
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.