1. Purpose
add_action()→ Used to execute custom code at specific points (hooks) during WordPress execution.add_filter()→ Used to modify existing data before it is used or displayed.
2. Syntax
add_action( $hook, $function_to_add, $priority, $accepted_args );
add_filter( $hook, $function_to_add, $priority, $accepted_args );
They look almost the same. The main difference is what your function does.
3. Example of add_action()
Add a message before the post content:
function mytheme_before_content() {
echo '<p class="notice">Welcome to my blog!</p>';
}
add_action( 'the_content', 'mytheme_before_content' ); // action
✅ Runs code at the hook, doesn’t return modified content.
4. Example of add_filter()
Change the length of excerpts:
function mytheme_custom_excerpt_length( $length ) {
return 20; // modifies the value
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length' ); // filter
✅ Modifies a value and returns it back to WordPress.
5. Key Rule
- Actions → Do something. (output HTML, enqueue scripts, save data, etc.)
- Filters → Change something. (modify titles, text, content, classes, etc.)
6. Comparison Table
| Feature | add_action() | add_filter() |
|---|---|---|
| Purpose | Run code at a specific hook | Modify and return data |
| Return value | Nothing required | Must return a value |
| Example usage | Enqueue styles, add meta box, display HTML | Modify excerpt length, change title, filter content |
| Hook type | Action hook | Filter hook |
✅ In short:
- Use
add_action()when you want to add functionality. - Use
add_filter()when you want to change/modify data.