I keep seeing add_action and add_filter. When should I use each, and why does my filter break the page when I forget to return something?
DEV3 Developer Forum
What is the difference between actions and filters in WordPress hooks?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
Both attach your callback to a named hook. The difference is intent and return value.
Actions let you do something at a point in execution. The return value is ignored.
add_action( 'wp_footer', function () {
echo '<!-- rendered -->';
} );
Filters modify a value and must return it.
add_filter( 'the_title', function ( $title, $post_id ) {
return is_singular( 'project' ) ? $title . ' (Project)' : $title;
}, 10, 2 );
If a filter callback returns nothing, the value becomes null, so titles or content go blank. That is the most common bug. Always return the (possibly modified) first argument.
Signature: add_filter( $hook, $callback, $priority = 10, $accepted_args = 1 ). Lower priority numbers run earlier. To receive more than one argument you must set $accepted_args.
Creating your own hooks so others can extend your code:
do_action( 'acme_after_save', $id );
$label = apply_filters( 'acme_button_label', 'Save', $id );
Removing hooks: remove_action( 'wp_head', 'wp_generator' ); The priority and callback must match what was added. For a class method, you need the same object instance, or use a closure variable.
Useful hooks to know: init, wp_enqueue_scripts, save_post, pre_get_posts (change main query), the_content, template_redirect, admin_menu.
Pitfall: running code too early, for instance calling is_singular() before the query exists. Use wp or template_redirect or later.