How and When to Use Actions and Filters

Wordpress Filters and Actions - When to Use Them

WordPress allows web developers to add their own code during the execution of a request by providing various hooks. These hooks come in the form of actions and filters:

  • Actions: WordPress invokes actions at certain points during the execution request and when certain events occur.
  • Filters: WordPress uses filters to modify text before adding it to the database and before displaying it on-screen.

The number of actions and filters is quite large, so we can’t get into them all here, but let’s at least take a look at how they are used.

Here’s an example of how to use the admin_print_styles action, which allows you to add your own stylesheets to the WordPress admin pages:

add_action('admin_print_styles', 'myplugin_admin_print_styles');

function myplugin_admin_print_styles() {
    $handle = 'myplugin-css';
    $src = MYPLUGIN_PLUGIN_URL . '/styles.css';

    wp_register_style($handle, $src);

And here’s how you would use the the_content filter to add a “Follow me on Twitter!” link to the bottom of every post:

add_filter('the_content', 'add_twitter_link_to_the_content');

function add_twitter_link_to_the_content($content) {
    $output = $content;
    $output .= '<p>';
    $output .= '<a href="">Follow me on Twitter!</a>';
    $output .= '</p>';
    return $output;

It’s impossible to write a WordPress plugin without actions and filters, and knowing what’s available to use and when to use them can make a big difference.

See the WordPress codex page “Plugin API/Action Reference” for the complete list of actions and the page “Plugin API/Filter Reference” for the complete list of filters.

Note: Pay close attention to the order in which the actions are listed on its codex page. While not an exact specification, my experimentation and trial-and-error has shown it to be pretty close to the order in which actions are invoked during the WordPress request pipeline.

Comments are closed.