Actions do stuff, filters change stuff

Home / WordPress / Actions do stuff, filters change stuff

This post is going to be a bit different – it will summarize actions and filters that exist within WordPress ecosystem. There are numerous articles describing action and filter hooks and all that information might appear overwhelming. From all the talk and information about hooks, I find these definitions to explain it in the best way:

  • Actions allow you to add extra functionality at a specific point in the processing of the page.
  • Filters allow you to intercept and modify data as it is processed.


Actions

You’ll find two functions when it comes to action hooks (there are more than two, though, such as remove_action(), but we are not interested in them at this point):

The first question would normally be – when to use either of these? It may be a very rough answer, but I’ll give it a shot:

  1. If you’re developing a theme or a plugin, there is a chance that you will use both.
  2. If you’re making some customizations on a theme (adding some functionality) or a plugin, it is likely that you will need add_action only.

Let’s have a look at wp_footer() function, which also exists as an action hook.

This is copied directly from WordPress core. If we want to output something (such as function) into wp_footer() action hook, we would use add_action:

At this point, the logical question is – how do I know if there is an action hook (that I would need at a certain point) available for the theme, plugin or WordPress? You will need to dig into documentation – for WordPress, you can find all the action hooks inside official code reference. Advanced plugins such as WooCommerce also have a generous list of hooks – take a peek.

To conclude – action hooks don’t change what’s already there, they are used for adding something new instead.


Filters

Filter is another type of hook and comes in two flavors (as with action hooks, there are some other filters available, but we are not interested in them at this point):

The difference is the same as it is the case with action hooks – if you are developing something from scratch, you will likely use apply_filters.  On the other hand, if you are doing some changes on the existing themes are plugins, you will use add_filter. As an example, let’s create a function that will not earn us the best developer award – it will only disable the logout link in the WordPress admin area. Let’s have a look at the wp_logout_url() function and logout_url filter (copied directly from WordPress core):

For this purpose, we will want to change the $logout_url variable only, so we will use add_filter() in the following way:

The possibilities of filters are endless, since filter hooks are frequent in many plugins, themes and most importantly – WordPress core has numerous filters available, allowing us to change practically every single part of it.