Site icon Treehouse Blog

Learn the Types of Hooks in WordPress

Hooks in WordPress

Hooks in WordPress allow developers to easily tie their own code in with the WordPress core code base, themes, and plugins. In this article, we’ll discover what hooks are, go over the different types of hooks, and look at a few examples of hooks in action.

Definition of Terms

A Hook is a generic term in WordPress that refers to places where you can add your own code or change what WordPress is doing or outputting by default. Two types of hooks exist in WordPress: actions and filters.

An Action in WordPress is a hook that is triggered at specific time when WordPress is running and lets you take an action. This can include things like creating a widget when WordPress is initializing or sending a Tweet when someone publishes a post.

A Filter in WordPress allows you get and modify WordPress data before it is sent to the database or the browser. Some examples of filters would include customizing how excerpts are displayed or adding some custom code to the end of a blog post.

At first, it may be a little confusing to figure out whether something is an action or a filter. The important difference is that when you work with a filter, you are going to receive some piece of data and then, at the end of your function, you have to return that data back. With an action, on the other hand, you are not receiving and modifying data, you are simply given a place in the WordPress runtime where you can execute your code.

Related Reading: The Perfect WordPress Inline SVG Workflow

Action and Filter Hooks

The WordPress Codex has two important pages that can help you orient yourself with what hooks are available in WordPress.

NOTE: At the time of writing there is a bit of a transition of documentation on hooks from the Codex to the Code Reference site. Because of this you may find hooks that are listed on the Codex, but not documented. You should be able to find some documentation for all of the hooks if you search for them in the Code Reference, however, it does not have any current pages like the Codex where all hooks are grouped in one place.

The WordPress Action Reference page has available actions listed by the following categories:

The Codex also has a similar Filter Reference page, which it lists by the following categories:

Many of these filter hooks are separated into subcategories: Database Reads and Database Writes. This depends on whether you are reading from the database prior to displaying on a page or editing a screen, or you are writing code prior to saving data to the database.

Working with hooks in WordPress starts with figuring out what hook you need to tie your code into and then writing the code to modify the data you need or run whatever action you need.

If you get stuck or you are not sure which hook to use, you can usually figure it out by searching for something like: “WordPress action for [whatever you want to hook into].”  The WordPress StackExchange has a number of results with questions like this as well.

How to Add and Remove Your Own Functions

If you would like to hook in your own functions, the process is quite simple. You first need to know a few pieces of information. For actions, you’ll want to know the name of the hook, as well as when exactly it runs. For filters, you also need to know the name of the hook, but you want to know what value you are going to get and have to return, as well. The final bit of information you need is the name of the function where you have all your code.

How to Hook into an Action

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

The required parameters of the add_action function are the hook and function to add. The priority is an optional integer value based on a scale of 1 to 999 that determines the priority of order for functions tied to that specific hook. Higher priority means it runs later, lower priority means earlier. The last parameter is used less often and it is for when you need to pass or accept multiple arguments.

How to Hook into an Filter

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

The add_filter works the same way as add_action. You will also have to be careful because sometimes a hook exists as both an action and a filter, or a filter and a function. You will see the real difference with the actual function you call.

Remember that, for a filter, the function_to_add both receives a value and has to return it at the end of the function. Actions, on the other hand, simply run the code they need to and don’t return a value.

How to Unhook from Actions and Filters

To remove a hook is quite simple. Use the function remove_action or remove_filter along with the name of the hook, function, and priority. The priority is optional and helpful if you have to unhook a function that is hooked more than once and you only want to remove a specific occurrence of that function.

remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );

Now that we have looked at the basics of how functions are hooked and unhooked, let’s take a look at a few real world examples of some different hooks in action.

Examples of WP Hooks

More than 200 hooks exist in WordPress. Below you will find a few examples of common hooks in use.

Register a Custom Menu in the Admin

function register_my_custom_menu_page() {
 add_menu_page( 'custom menu title', 'custom menu', 'manage_options', 'myplugin/myplugin-admin.php', '', 'dashicons-admin-site', 6 );
}
add_action( 'admin_menu', 'register_my_custom_menu_page' );

In the example above you can see the function register_my_custom_menu_page being hooked into the admin_menu action hook. This allows you to run code when the admin menu is being generated. This is most commonly used to add a custom menu link for a plugin or theme.

Related Reading: Create Your First WordPress Custom Post Type

Change the Excerpt Length

function excerpt_length_example( $words ) {
 return 15;
}
add_filter( 'excerpt_length', 'excerpt_length_example' );

In this example, we are using the excerpt_length filter, which provides us with an integer that determines the length used with the_excerpt(). If you are unsure about what value is passed to a filter, you can search the WordPress core code for apply_filters( ‘filter_name’ and look deeper into what is going on with that filter.

Hook into Post Publishing

function publish_post_tweet($post_ID) {
  global $post;
  // Code to send a tweet with post info
}
add_action('publish_post', 'publish_post_tweet');

In the pseudo example above, you can see that we are hooking into an action called “publish_post” which runs when a post is published. You could use this to do something like sending a tweet with information about the published post.

The actual code for this is more complex than we have space to cover, but it serves as a good example of an action you can run when a post is published.

Hook Into Widget Initialization 

function create_my_widget() {
 register_sidebar(array(
 'name' => __( 'My Sidebar', 'mytheme' ), 
 'id' => 'my_sidebar',
 'description' => __( 'The one and only', 'mytheme' ),
 ));
}
add_action( 'widgets_init', 'create_my_widget' );

Creating a widget is a very simple and common action to add to a theme or plugin. When you do so, you have to hook into the widget_init action. This hook lets you run your code when widgets are being generated within WordPress, so it’s the perfect hook to add your own widgets at the same time.

Hook Into Front-end Scripts and Styles

function theme_styles() {
 wp_enqueue_style( 'bootstrap_css', get_template_directory_uri() . '/css/bootstrap.min.css' );
 wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );
 wp_enqueue_script( 'bootstrap_js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true );
 wp_enqueue_script( 'theme_js', get_template_directory_uri() . '/js/theme.js', array('jquery', 'bootstrap_js'), '', true );
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );

This is a commonly-used hook and one that you learn quite early in WordPress development. It allows you to generate a URL stylesheets and JavaScript files on the front-end of your theme. This is the preferred method of linking to CSS and JS, rather than hardcoding the links in your theme header.

Dig Deeper Into Hooks

This article serves as a very basic introduction to working with hooks in WordPress. If you would like to go deeper, I suggest checking out my course on WordPress Hooks – Actions and Filters, now available at Treehouse!

To improve your coding skills, check out the Treehouse 7-day free trial!

Exit mobile version