DJ Quilter

Front-End Developer

Explaining WordPress Action Hooks

WordPress Action Hooks are one of those ideas that I have previously wanted to learn more about, but was held back by the way in which they were explained both on the WordPress Codex and in articles written by other developers. I got to grips with them in a recent project and was stunned by not only the simplicity of the idea, but also by the lack of any clear explanation of the concept.

Simply put, an action hook is made up of two parts:

The Action
This is what you want to happen; your code within a function.
The Hook
The time at which you want to run your code.

WordPress defines the available hooks for you, so all you need to do is write your function and then tie it to the hook in functions.php. This should look something like this:


add_action( 'init', 'my_action' );
function my_action() {
  // Your code lives here
}

The ‘add_action’ function is what ties the action to the hook. It says “run this code, at this time”, which in this case is at ‘init‘. The ‘my_action’ function is your code.

The hooks that you can use are listed on the WordPress Codex. I have mainly added my own custom actions to the ‘init’ hook, which I would imagine is due to my working with a lot of forms. WordPress describes the ‘init’ hook as follows:

Runs after WordPress has finished loading but before any headers are sent. Useful for intercepting $_GET or $_POST triggers.

Another hook that I regularly use is ‘wp_enqueue_scripts‘. Even if you haven’t purposefully used it in a WordPress project, you’ll probably still find it in your functions.php file. It is the proper way of adding scripts to your WordPress site.


add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
  wp_enqueue_script( 'my-script', get_template_directory_uri().'/js/my-script.js' );
}

Again, the ‘add_action’ function ties our function to a specific hook and in this case, our Javascript file gets added to the head of our site. Simple.

That’s really all you need to know about action hooks. As you’re building your custom functions, you just need to make sure you understand the reasons why you’re assigning your action to a specific hook, and there’s not much chance that you’ll go wrong!