WordPress Hooks & Filters

April 21, 2014

 - Tags: ,

When developing WordPress theme & plugins, it is absolutely necessary to understand action and filter hooks. Action and filter hooks are very important parts of WordPress core code which allows developer to customize and add new features to WordPress. Oftentimes these two concepts are misunderstood in the community, so I wanted to write an article to clarify a bit.

What happen when the page loads ?

In order to understand the concepts of action and filter hooks, let’s first focus on what happen when a user sends a request to WordPress. To make it simple, the process can be broken down like this:

  1. User sends a request from his browser
  2. Server receives request and pass it to WordPress
  3. The index.php file initiates the loading sequence
  4. The basic parameters are loaded by wp-config.php
    (database connection parameters, etc..)
  5. The core files of WordPress are loaded
  6. The active plugins are loaded
  7. The theme is loaded
  8. The user request is processed by the theme templates.
  9. If necessary, queries are sent to database to fetch dynamic content
  10. Finally, the php templates finish to render the html file, which is sent to the user

While I reckon it might be difficult to keep up with all the stages, what is important to understand is that action hooks and filters are sort of milestones defined all along the page loading process. More precisely, action hooks and filters are defined in the different php files used by WordPress during the loading process.

Ok, great, now, what do we do with them ? We use them to add our own code to WordPress core files or to filter data.

Action hooks

Action hooks are used to trigger an action by adding code at a specific time in the page loading process (or in a specific location of a WordPress core file, if you prefer this definition). When using an action we have to use a function called add_action():

add_action( $hook, $function_to_add, $priority, $accepted_args );

Required arguments: $hook and $function

The first two arguments are both the most important one. The $hook argument is the name of the hook, while the $function argument is the name of the function to be run when the $hook is triggered, otherwise known as the callback function.

In Javascript terms:

  • $hook is the name of the Event we listen to
  • $function is the name of the EventHandler

I know this definition probably will displease some php purists, but I found it useful for better understanding hooks.

Optional arguments: $priority and $accepted_args

Then, we still have two optional arguments $priority and $accepted_args, which are used less often. $priority, according to the Codex is:

used to specify the order in which the functions associated with a particular action are executed

$priority can be quite useful when we have to deal with third-party code. For example, you may want your callback function to run before all or after all other callback functions associated with this hook (e.g some plugins might also have attached callback functions to the same action hook as you). The lower the number, the earlier your function will be executed.

Finally we have $accepted_args, used to specify how many arguments the callback function accepts. The default value of this argument is 1, so if your callback function accepts more arguments, make sure to specify it with $accepted_args.

Example

Let’s say we want to enqueue our css stylesheets in the <head> section of our html document:

<link rel='stylesheet' id='google-fonts'  href='fonts.googleapis.com/css?family=myfont' type='text/css'>
<link rel='stylesheet' id='bootstrap'  href='mywebsite.com/wp-content/themes/my-theme/bootstrap/bootstrap.css' type='text/css'>
<link rel='stylesheet' id='my-style'  href='mywebsite.com/wp-content/themes/my-theme/style.css' type='text/css'>

To do this in WordPress, we have to add the following snippet to functions.php:

function add_my_scripts() {
wp_enqueue_style( 'google-fonts', 'fonts.googleapis.com/css?family=myfont' );
wp_enqueue_style( 'bootstrap', get_template_directory_uri()  . '/bootstrap/bootstrap.css' );
wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );

First, we define add_my_scripts(), our callback function, inside which we enqueue our stylesheets with the wp_enqueue_style() function.

Then, we use the function add_action() to attach our callback function to the the action hook we want to use (i.e wp_enqueue_scripts).

Et voila ! This is a very basic use of an action hook. But we can also use action hooks for more complex tasks. for example, if we are building a plugin for blog subscription, we could attach a send_notification_email() function to the save_post action hook.

  • Note 1: Although add_my_scripts is indeed a function, you should NOT use parentheses when passing it as a callback to add_action. As a side note, generally speaking in PHP follow the same rule whenever you need to pass the name of a callback function as an argument of another function.
  • Note 2: It doesn’t matter in which order you write this snippet: add_my_scripts() first then add_action(), or the other way around, both will work.

Filter hooks

Filter hooks are very similar to Action hooks, except than instead of being for used for triggering an action, there are used for filtering data.

Some developers have a hardtime choosing when to use an action hook and when to use a filter hook. Actually, it’s pretty simple. You just need to ask yourself this question:

Another consideration that may help you to choose is that filter hooks return a value, while action hooks do not.

Back to filter hooks now. To use a filter hook, you need to use the function add_filter():

add_filter( $tag, $function_to_add, $priority, $accepted_args );

Required arguments: $tag and $function_to_add

$tag is to add_filter() what $hook is to add_action(), i.e it used to specify which filter hook you want to attach your callback function to. As for the other arguments, there are very similar to the one of add_action().

Example

Let’s say we have a plugin that let users use shortcodes in widgets. For example, a pair of shortcodes in the WordPress widget editor is used to wrap some content with a bootstrap row in the html document.

In the WordPress widget editor, users type this:
[row] My content [/row]

In the html document, it becomes this:
<div class="row">My content</div>

To make it work, we would need to attach the do_shortcode() callback function to the widget_text filter hook:

add_filter('widget_text', 'do_shortcode');

So now, the content of the widget text stored in the database will be processed by do_shortcode() before being output to the html document. If the widget text contains any pre-defined shortcode, it will be converted to its html equivalent.

Creating custom action hooks and filter hooks

Finally, what if you want to use action or filter hooks that are not defined in WordPress core code ? For this, you would need to define your own action hooks and filter hooks with do_action() and apply_filters().

Custom action hooks

To create an action hook, you need to use the do_action() function, and pass it the name of your action hook (i.e $tag ), as well as the argument(s) accepted by the function callbacks (i.e $arg ):

do_action( $tag, $arg );

So as an example, we could use this code:

// Define the arguments that will be passed to the callback function
$a = array(
	 'eye patch' => 'yes'
	,'parrot' => true
	,'wooden leg' => (int) 1
);
//Create the action hook
do_action( 'my_action_hook',  $a);

To be more clear, when I will use this action hook in my code, my callback function will receive $a as its arguments:

function my_callback_function($arg) { 
//$arg = $a
//$val['eye patch'] = 'yes'
//$val['parrot'] = true
//$val['wooden leg'] = 1
...
...
}
add_action( 'my_action_hook', 'my_callback_function' );

Custom filter hooks

To create filters, the procedure is quite similar. We use the function apply_filters():

apply_filters( $tag, $value, $var ... );

Let’s first create a filter hook who would filter the value of the website title:

$title = get_the_title( $ID );
$my_custom_title = apply_filters('the_title', $title );

In our theme function.php let’s use this filter hook:

function my_custom_filter($raw_title) {
  return $modified_title = $raw_title . "my-custom-string";
}
$my_custom_title = add_filter('the_title', 'my_custom_filter' );

Please note that this snippet was given as an example only. If you really want to filter the title, no need to use apply_filter(), as the appropriate filter hook already exists in WordPress core code (i.e wp_title).

Conclusion

In this article, I explained that WordPress hooks and actions filters are events defined in the WordPress core code. We use them to customize or extend the features of WordPress.

  • I first explained the general loading process of WordPress.
  • Then I introduced action hooks and filter hooks, as well as some practical examples.
  • I also explained that although similar, action hooks and filter hooks were a bit different in that action hooks are used to trigger an action, without returning a value, while filter hooks are used to filter data, and they return a value.

If you would like to know more about action hooks and filter hooks, please check out the links in the below section ‘Additional Ressources’. Alternatively, you could check out my article on Theme Hooks. Finally, if you are interested in knowing more about some other WordPress concepts mentioned in this article, you can read my articles on Shortcodes and Stylesheet & Scripts Enqueuing

Additional Resources

Leave a Reply