WordPress actions and filters with practical examples
WordPress is built on hooks: they let you change almost anything without editing core files. There are two kinds. An action lets you do something at a certain moment: send an email, save a record, load a script. A filter lets you change data before it is used or displayed: a title, a price, a URL. Understanding the difference is one of the first skills of a WordPress developer.
Problem: You need to run your code at a certain moment (an action) or change data before it is output (a filter), and you are not sure about the syntax and where to put the code.
Solution: add_action() attaches a function to an action, which WordPress (or a plugin) runs with do_action(). add_filter() attaches a function to a filter run with apply_filters(); the function receives the value and must return it. The examples go into functions.php.
An action
Send the administrator an email when a new user registers:
<?php
add_action( 'user_register', 'helloadmin_notify_on_register', 10, 1 );
function helloadmin_notify_on_register( $user_id ) {
$user = get_userdata( $user_id );
wp_mail( get_option( 'admin_email' ), 'New user registered', 'Username: ' . $user->user_login );
}
The third argument is the priority (default 10, lower numbers run earlier), the fourth is how many arguments the function accepts.
A filter
Change the excerpt length and the “read more” text:
<?php
add_filter( 'excerpt_length', 'helloadmin_excerpt_length' );
function helloadmin_excerpt_length( $length ) {
return 30; // words
}
add_filter( 'excerpt_more', function ( $more ) {
return '…';
} );
A filter function must always return a value. If it returns nothing, the data becomes empty: a filter on the_title without return removes all titles on the site.
Your own hook
A theme or plugin can give others a place to plug in:
<?php
// In the template
do_action( 'helloadmin_before_profile', $user_id );
$title = apply_filters( 'helloadmin_profile_title', __( 'Profile', 'theme-name' ), $user_id );
// Somewhere else, for example in a child theme
add_action( 'helloadmin_before_profile', function ( $user_id ) {
echo '<div class="profile-banner">Welcome!</div>';
} );
Removing a hook
To remove a function added by a theme or plugin, call remove_action() or remove_filter() with the same hook, function and priority, and do it after it was added:
<?php
add_action( 'init', function () {
remove_action( 'wp_head', 'wp_generator' );
} );
NOTE: A hook added with an anonymous function cannot be removed with remove_action(), because there is no name to pass. For code that others may want to switch off, use named functions. To see what is attached to a hook, use Query Monitor or var_dump( $GLOBALS['wp_filter']['wp_head'] );. Scripts and styles are also added through a hook, see enqueueing scripts and styles correctly.