How to Use Actions, Filters, and Custom Hooks

How to Use Actions, Filters, and Custom Hooks

WordPress Hooks are one of the most important tools to have in a WordPress developer’s arsenal. They’re the foundation of WordPress plugin and theme development. You can use WordPress’ many built-in hooks to ‘hook into’ the WordPress Core with your custom code and do or modify something. There are two types of WordPress hooks: Actions and Filters. Hooks are so common that even WordPress Core uses them extensively itself. WordPress also includes a way for you to define your own custom hooks so that other developers can hook into your code. Learning how actions, filters, and custom hooks work is essential to master WordPress development. The first half of this article covers the basics of WordPress hooks and explains how they work with multiple examples. In the second half, you’ll learn how you can use hooks to customize WordPress, create your own custom hooks, and use them to build your own extensible plugins. Sounds exciting? Let’s dive in! What Are WordPress Hooks? A WordPress page is assembled by tons of functions and database queries. The WordPress Core, plugins, and theme work together to output the page elements like text, images, scripts, and styles. Once fully assembled, the browser then puts them all together and renders the page. WordPress hooks allow you to ‘hook into’ this build process at certain points and run your custom code. The main function of hooks is to allow you to modify or add features to WordPress without touching the core files. See how Kinsta stacks up against the competition. Select your provider WP Engine SiteGround GoDaddy Bluehost Flywheel HostGator Cloudways AWS Digital Ocean DreamHost Other Compare Hooks will help you extend WordPress with your own code The WordPress Plugin API powers the functionality of WordPress hooks. You use hooks by calling certain WordPress functions called Hook Functions at specific instances during the WordPress runtime. Using hook functions, you can bundle your custom code within a Callback Function and have it registered with any hook. Once registered, this callback will run wherever the hook is, allowing you to augment or replace the default WordPress features. The hook’s position in the code execution process is an important factor. You’ll learn more about its significance in the upcoming sections. Get hooked on #webdev with this guide to WordPress hooks. ⚡️Click to Tweet Two Types of WordPress Hooks: Actions and Filters WordPress includes two types of hooks called Actions and Filters. Actions let you do something at certain predefined points in the WordPress runtime, while Filters let you modify any data processed by WordPress and return it. Actions are defined in the WordPress code as: do_action( ‘action_name’, [optional_arguments] ); The action_name string is the name of the action. You can specify the [optional_arguments] variable to pass additional arguments to the callback function. If this field is not specified, then its default value will be empty. Example: The do_action( ‘wp_head’ ) action can be hooked in to run custom code every time WordPress processes the site header. This action doesn’t have any other arguments. Filters are defined in the WordPress code as: apply_filters( ‘filter_name’, ‘value_to_be_filtered’, [optional_arguments] ); The filter_name string is the name of the filter, the value_to_be_filtered variable is the value that needs to be filtered and returned, and the [optional_arguments] variable can pass additional arguments, just like with actions. Example: The apply_filters( ‘admin_footer_text’ , string $text ) filter can be hooked in to modify the text displayed in the admin footer. As of WordPress 5.4, its default value will display the sentence Thank you for creating with WordPress. in the admin area footer. You’ll learn how to hook into actions and filters later with many examples from the WordPress Core. Once hooked, you can direct your code to do or customize something on your site. For instance, you can use hooks to send an automated email after publishing a post, or load custom stylesheets to change the appearance of your site. WordPress hooks help you interact with or modify your website The simplest way to understand hooks is to imagine your WordPress website as building a house. Hooks are akin to using a crane to move construction items back and forth. The items being transferred are the Callback Functions which include your custom code. These items (or functions) can help you build or modify the house. Example of hooking into the ‘wp_head’ action in WordPress Callback functions can be regular PHP functions, default WordPress functions, or custom functions defined by you. We can only carry certain items on specific carriers attached to particular hooks. Thus, actions can only be hooked with Action Functions. Likewise, filters can only be hooked with Filter Functions. While it’s tedious to change the hooks and carriers on a crane, WordPress makes it super easy by including over 2,200 types of default hooks. WordPress 5.1 has 2200+ native hooks (Source: Adam Brown) You can find hooks spread across the WordPress Core, allowing you to tap into the exact position where you want to hook in to and run your custom code. WordPress hooks allow you to ‘hook into’ the page building process …and give you more control over what you create.⚡️Click to Tweet Hooks vs Actions vs Filters As per the WordPress Plugin Handbook: “Hooks are a way for one piece of code to interact/modify another piece of code…There are two types of hooks: Actions and Filters.” There’s widespread inconsistency with how the terms Hook, Action, and Filter are used. A few tutorials and guides mix them up with the functions associated with them. A major reason this confusion exists is because of the complex nature of how hooks work. Even when you look carefully inside the WordPress Core, you’ll find that there’s not much difference between adding actions and filters. Here’s the source code for the add_action() function from the wp-includes/plugin.php file: function add_action( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {      return add_filter( $tag, $function_to_add, $priority, $accepted_args ); } The add_action() function just calls the add_filter() function and returns its value. Why? Because they both fundamentally work the same way, except for one difference. The apply_filters() function returns a value that can change existing data types, while the do_action() function returns nothing (NULL value in PHP). If you’re still confused, don’t fret! Once you’re through the first half of this article, all will be clear. We’ll stick to the official WordPress Codex terminology as it’s clear, precise, and universal. For now, familiarize yourself with the hook routine shown below. The Hook Routine: Hooks, Hook Functions and Callback Functions Let’s break down the differences between Actions and Hooks. WordPress Hooks Actions Filters Actions are used to run custom functions at a specific point during the execution of WordPress Core. Filters are used to modify or customize data used by other functions. Actions are defined/created by the function do_action( ‘action_name’ ) in the WordPress code. Filters are defined/created by the function apply_filters( ‘filter_name’, ‘value_to_be_filtered’ ) in the WordPress code. Actions are also called Action hooks. Filters are also called Filter hooks. Actions can only be hooked in with Action functions. E.g. add_action(), remove_action(). Filters can only be hooked in with Filter functions. E.g. add_filter(), remove_filter(). Action functions need not pass any arguments to their callback functions. Filter functions need to pass at least one argument to their callback functions. Action functions can perform any kind of task, including changing the behavior of how WordPress works. Filter functions only exist to modify the data passed to them by the filters. Action functions should return nothing. However, they can echo the output or interact with the database. Filter functions must return their changes as output. Even if a filter function changes nothing, it must still return the unmodified input. Actions can execute almost anything, as long as the code is valid. Filters should work in an isolated manner, so they don’t have any unintended side effects. Summary: An action interrupts the regular code execution process to do something with the info it receives, but returns nothing back, and then exits. Summary: A filter modifies the info it receives, returns it back to the calling hook function, and other functions can use the value it returns.   Sometimes, you can use either an action or a filter to accomplish the same goal. For instance, if you want to modify the text in a post, you can register a callback function with the publish_post action and change the post content when it’s being saved to the database. // define the callback function to change the text function change_text_callback() { // add the code to change text here } // hook in to the ‘publish_post’ action with the add_action() function add_action( ‘publish_post’, ‘change_text_callback’ ); Or you can register another callback function with the_content filter to modify the post content before it’s displayed in the browser. // define the callback function to modify the text function change_text_another_callback( $content ) { // add the code to change text here and then return it return $filtered_content; } // hook in to ‘the_content’ filter with the add_filter() function add_filter( ‘the_content’, ‘change_text_another_callback’); Two different approaches with the same result. Knowing when to use one over the other is key to being a good WordPress developer. How Do WordPress Hooks Work? The house example was simple enough to understand the basic functioning of hooks, but it doesn’t capture the complexity of how they work. Most importantly the concepts of hook position and specificity. A better example would be to imagine processing a WordPress webpage as assembling a car. Unlike manufacturing a car, which takes time, assembling a webpage is almost instantaneous. Assembling a webpage is like assembling a car Much like how a car is put together part-by-part in a modern assembly line, a WordPress webpage is assembled element-by-element by the server and the client. The WordPress Core is like the car engine, chassis, and other essentials, powering the “core” functionality of the website. You can have a functional website with just the WordPress Core, but where’s the fun in that? You need to add exciting features to the site. That’s where WordPress plugins and themes step in, both of which use hooks extensively. In the example above, every numbered station is like a hook inside the WordPress Core. There are two kinds of stations, like actions and filters. Each station includes a specific type of slot that only accepts certain tools, akin to action functions and filter functions. All the stations are placed at frequent intervals for modularity and efficiency. Depending on the requirement at a particular position, we can attach (or hook) the most appropriate tool for the job at that specific station. These tools are like the callback functions used to interact with or modify WordPress. Some tools can significantly alter the working of the car, much like callbacks registered to actions. Other tools are only used to customize the appearance of the car, like callbacks registered to filters. Using the right tools at the right stations is crucial to build a top-notch car. In the same way, hooks help us customize WordPress as per our unique needs. If you extend this analogy, plugins are like adding helpful automobile features such as airbags, entertainment console, remote keyless system, etc (like these to enhance WooCommerce’s functionality). Themes are analogous to customizing the visual part of the car, like the overall design, paint job, rims, etc. (here’s how to customize your WordPress theme). Where to Register Hooks and Their Functions? There are two recommended ways to add hooks in WordPress: Plugins: Make your own plugin and add all your custom code within it. Child Themes: Register the hooks and callback functions in your child theme’s functions.php file. For this tutorial, let’s start by creating a plugin. To do that, create a new folder in your /wp-content/plugins/ directory. I’m naming my plugin salhooks, but you can name it anything you want. As per WordPress guidelines, you need to create a PHP file with the same name (salhooks.php) inside your plugin directory. Add the following header fields to your plugin file to register it with WordPress. You can learn more about plugin header requirements in the WordPress Codex.

Leave a Reply

Your email address will not be published. Required fields are marked *