How and When to Use Actions and Filters

July 2, 2013 in Blog by

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.

About Milan

The founder of Dessky, Milan has worked in all aspects of advanced web development, from building large commercialized e-commerce and social network systems to troubleshooting small wordpress blogs. His extensive skills cover virtually every area of web development. Milan works hard to implement tomorrow’s trends utilizing the cutting edge systems of today. He specializes in rich internet web application development and deployment, complex HTML5/CSS3 graphical design layouts, full blown framework-driven rich internet applications, and much more. Milan provides elegant solutions to complex problems encountered by businesses that use internet based services. Also he is the Graduated Engineer of both Computer Science and Information Technology.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 1.00 out of 5)

Leave a Reply

Your email address will not be published. Required fields are marked *