Back to Blog

Understanding WordPress Hooks: A Beginner's Guide to Actions and Filters

ABBy Ajaya BK

Published on July 28, 2024

7 min read
Understanding WordPress Hooks: A Beginner's Guide to Actions and Filters

Introduction: The Secret to WordPress's Flexibility

If you've ever delved into the world of WordPress theme or plugin development, you've undoubtedly come across the terms 'actions' and 'filters.' These are the two types of hooks, and they are the absolute cornerstone of WordPress development. Hooks are, in essence, the secret to WordPress's incredible flexibility. They are specific points in the WordPress code where developers can 'hook in' their own custom functions to change how WordPress behaves without ever modifying the core files of WordPress itself.

Understanding hooks is the key to graduating from being a WordPress user to a WordPress developer or power user. It allows you to add functionality, modify existing features, and integrate with other services in a way that is clean, scalable, and—most importantly—update-safe. When you edit a core file, your changes get wiped out the next time WordPress updates. When you use a hook, your customizations are safely contained within your theme's functions.php file or your own custom plugin, and they continue to work after updates. This guide will demystify hooks, explaining the difference between actions and filters with clear, practical examples.

What Are Hooks?

Imagine the WordPress core code is a factory assembly line. As a piece of data (like a blog post) moves down the line, it goes through various stations where it gets processed. Hooks are like designated service ports at these stations. WordPress essentially announces, 'Hey, I'm at the save_post station right now. Does anyone want to do anything?' or 'I'm about to display the post title, the_title. Does anyone want to change it before it goes out?'

  • Actions allow you to do something at a specific point.
  • Filters allow you to change something (modify data) before it's used.

That's the fundamental difference. Actions are for running your own code at a certain event, while filters are for intercepting and modifying data that WordPress is processing.

Actions: Firing Custom Code on WordPress Events

An action is triggered when a specific event occurs in WordPress, like a post being published, a user logging in, or the header of the page being loaded. You use the add_action() function to attach your custom function to a specific action hook.

The add_action() Function:

add_action( 'hook_name', 'your_custom_function_name', [priority], [accepted_args] );

  • hook_name: The name of the action you want to hook into (e.g., wp_head, save_post).
  • your_custom_function_name: The name of the PHP function you want to run.
  • priority (optional): A number that determines the order in which functions attached to the same hook are executed. A lower number runs earlier. The default is 10.
  • accepted_args (optional): The number of arguments your function accepts. The default is 1.

Practical Example 1: Adding Google Analytics to your Header

A very common task is to add a tracking script, like Google Analytics, to the <head> section of every page. The wp_head action hook is perfect for this. It fires right before the closing </head> tag.

// In your child theme's functions.php file

add_action( 'wp_head', 'add_google_analytics_script' );

function add_google_analytics_script() {
  ?>
  <!-- Google Analytics Tracking Code -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXXX-X');
  </script>
  <!-- End Google Analytics -->
  <?php
}

Here, we've told WordPress: 'At the wp_head event, please run my add_google_analytics_script function.' Our function then simply outputs the required script.

Practical Example 2: Sending an Email Notification When a Post is Published

The publish_post hook is triggered whenever a post is published. We can use this to send an email notification to the site administrator.

// In your child theme's functions.php file

add_action( 'publish_post', 'notify_admin_on_publish', 10, 2 );

function notify_admin_on_publish( $ID, $post ) {
  $admin_email = get_option( 'admin_email' );
  $subject = 'A new post has been published: ' . $post->post_title;
  $message = 'A new post, "' . $post->post_title . '", has just been published on your website.';
  $message .= '\n\nView the post: ' . get_permalink( $ID );

  wp_mail( $admin_email, $subject, $message );
}

In this example, we're using the publish_post hook and telling it our function (notify_admin_on_publish) accepts two arguments (10, 2). These arguments, the post ID and the post object, are passed to our function by WordPress, allowing us to use the post's title and permalink in our email.

Filters: Modifying Data on the Fly

A filter hook gives you the opportunity to intercept a piece of data, modify it, and then return it. WordPress passes a variable to your function, your function does something to it, and then it must pass it back. This is used everywhere in WordPress to change text, modify query results, or alter HTML output.

The add_filter() Function:

add_filter( 'hook_name', 'your_custom_function_name', [priority], [accepted_args] );

The structure is identical to add_action(). The key difference is that a filter function must return a value.

Practical Example 1: Customizing the 'Read More' Link Text

By default, WordPress excerpts end with [...]. We can use the excerpt_more filter to change this to a custom 'Read More' link.

// In your child theme's functions.php file

add_filter( 'excerpt_more', 'custom_excerpt_read_more' );

function custom_excerpt_read_more( $more ) {
  return '... <a class="read-more" href="' . get_permalink() . '">Read More</a>';
}

Here, WordPress passes the default [...] text into our function as the $more variable. We ignore it and instead return our own custom HTML string. This returned value is what WordPress will now use.

Practical Example 2: Adding a Class to the Body Tag

The body_class filter allows you to programmatically add CSS classes to the <body> tag of your website. This is incredibly useful for styling specific pages differently.

// In your child theme's functions.php file

add_filter( 'body_class', 'add_class_for_specific_page' );

function add_class_for_specific_page( $classes ) {
  // is_page() checks if we are on a specific Page (by slug, title, or ID)
  if ( is_page('contact') ) {
    // Add our custom class to the array of classes
    $classes[] = 'contact-page-styles';
  }
  // IMPORTANT: Always return the full array of classes
  return $classes;
}

In this case, WordPress passes an array of existing body classes ($classes) to our function. We check if the current page is the 'Contact' page. If it is, we add our new class to the array. Then, we must return the modified $classes array.

Finding Hooks to Use

How do you know what hooks are available? This used to be difficult, but now there are great resources:

  • Official Developer Documentation: The WordPress Code Reference is the ultimate source of truth. You can search for functions and see a list of hooks they contain.
  • Searching the Core Code: You can search the WordPress source code for do_action(' to find action hooks and apply_filters(' to find filter hooks.
  • Plugin/Theme Documentation: Good plugins and themes (like WooCommerce or Elementor) will have extensive developer documentation listing all the custom hooks they provide.

Conclusion

Hooks are the foundation of professional WordPress development. They provide a safe and powerful way to extend and customize WordPress without creating future problems. By learning to use add_action() to fire your own code during key events and add_filter() to modify data before it's displayed, you unlock the full potential of WordPress and can start building truly custom, scalable solutions.

AB

Written by

Ajaya BK

Ajaya is a WordPress Virtual Assistant specializing in helping businesses set up, fix, and optimize their websites for speed, reliability, and clarity.

More about me