WordPress Action Hooks

WordPress Action Hooks are most important feature of WordPress for plugin developers. They allows plugin developers to "hook" into the WordPress workflow and change how it works without directly modifying the core.

WordPress has two primary types of hooks:

  • action hooks
  • filter hooks.

Action hooks allow you to execute a function at a certain point in the WordPress workflow. Filter hooks allow you to manipulate the output passed through the hook.

Action hooks

Action hooks gives you the ability to call a function at certain points in the WordPress loading process or when a specific event occurs. For example, you might use hooks to call a function to execute when:

  • WordPress first loads a page
  • A comment is post on a blog post
  • The admin deletes a blog post

This is all possible because of the do_action() function. Your plugin will hook into WordPress and indirectly access the do_action() function.

do_action()

This is what an action hook looks like:

<?php
do_action( $tag, ...$arg ) ;
?>
  • $tag — The name of the action hook.
  • ...$arg — Value(s) passed to registered actions. It is not necessarily a single argument. You can optionally pass any number of parameters or even none, depending on the hook.

With multiple parameters, the action hook would look like:

<?php
do_action( $tag, $arg_1, $arg_2, $arg_3 );
?>

As an example, let us look at how the wp_head action hook looks like in WordPress.

<?php
do_action( 'wp_head' );
?>

Just like that. It only has a name "wp_head" but passes no extra parameters. The wp_head action is fired within the <head> section on the front end of the site. It doesn’t do anything except provide WordPress and plugins a hooking point to add meta information, style sheets, scripts and anything that can be put in the head.

When fired in WordPress, this code looks for every action registered for the wp_head action hook and then executes those actions in the specified order.

Let us look at another example of an action hook. This one has two extra parameters, $post_ID and $post.

<?php
do_action('save_post', $post_ID, $post);
?>

However, a hook is nothing without an action.