How to Use WordPress Hooks: Actions and Filters Explained

If there's one concept that separates a beginner WordPress developer from an intermediate one, it's a thorough understanding of hooks.

WordPress hooks — actions and filters — are the mechanism that makes WordPress infinitely extensible without modifying core files. They're the foundation of every plugin you'll ever build, the reason themes can be customised cleanly, and the architectural pattern that enables thousands of plugins to coexist without conflict.

This guide explains hooks comprehensively — what they are, how they work, the difference between actions and filters, how to use them professionally, and common patterns and pitfalls.

What Are WordPress Hooks?

WordPress executes its code by working through a sequence of functions — loading the database, setting up the environment, loading plugins, setting up the theme, handling the request, generating output. As it progresses through this sequence, WordPress "fires" hooks at specific points.

A hook is a named signal that says: "This specific thing just happened (or is about to happen)."

Any plugin or theme can "hook in" — register a function to run when a specific signal fires. WordPress calls your function at exactly the right moment, without you needing to modify any core code.

This is called the Observer pattern in software design. WordPress is the observable subject. Your plugin functions are the observers.

Actions"This thing happened. Do something."
Filters"This value is about to be used. You can change it first."
01
Actions: Do Something When an Event Occurs

An action hook fires at a specific moment in WordPress's execution. Your action callback runs at that moment and performs a task — sending an email, logging data, creating database records, outputting content.

Adding an Action

PHP — Add Action Syntax
add_action( 'hook_name', 'your_callback_function', $priority, $accepted_args );

Parameters:

  • hook_name — The action hook to attach to
  • your_callback_function — The function to call when the hook fires
  • $priority — Execution order (default: 10; lower numbers run first)
  • $accepted_args — How many arguments to pass from the hook (default: 1)

Basic Action Example

PHP — Action Example
// Run a function when WordPress finishes loading
add_action( 'init', 'my_plugin_initialise' );

function my_plugin_initialise() {
    // Register a custom post type, flush rewrite rules, etc.
    register_post_type( 'portfolio', array(
        'public'    => true,
        'label'     => 'Portfolio',
        'supports'  => array( 'title', 'editor', 'thumbnail' ),
    ) );
}

Actions with Arguments

Some hooks pass arguments to your callback. Accept them by increasing $accepted_args:

PHP — Action with Arguments
// The 'save_post' action passes the post ID, post object, and update flag
add_action( 'save_post', 'handle_post_saved', 10, 3 );

function handle_post_saved( $post_id, $post, $update ) {
    // Skip auto-saves
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    // Skip if this is an update (only run on new posts)
    if ( $update ) {
        return;
    }

    // This is a newly published post — send a notification
    if ( $post->post_status === 'publish' ) {
        error_log( "New post published: {$post->post_title}" );
    }
}

Removing an Action

PHP — Remove Action
// Remove a function that was added elsewhere
remove_action( 'init', 'some_other_function', 10 );

// Remove a method from a class instance
// (Need reference to the same object)
 $class_instance = new MyClass();
add_action( 'init', array( $class_instance, 'init_method' ) );
remove_action( 'init', array( $class_instance, 'init_method' ) );

Creating Your Own Actions

You can fire custom hooks within your own plugin/theme code, allowing other developers to extend your code:

PHP — Custom Action Hook
// In your plugin:
function my_plugin_process_order( $order_id ) {
    // Do your order processing...
    $order_data = get_post_meta( $order_id );

    // Fire a custom hook so other code can react
    do_action( 'my_plugin_after_order_processed', $order_id, $order_data );
}

Other plugins or themes can then extend your plugin:

PHP — Hooking Into Custom Action
add_action( 'my_plugin_after_order_processed', function( $order_id, $order_data ) {
    // Send order to ERP system, update inventory, etc.
}, 10, 2 );
02
Filters: Modify a Value Before It's Used

A filter hook fires when WordPress (or a plugin/theme) is about to use a value. Your filter callback receives the value, can modify it, and must return it — either unchanged or modified.

Adding a Filter

PHP — Add Filter Syntax
add_filter( 'hook_name', 'your_callback_function', $priority, $accepted_args );

The syntax is identical to add_action. The difference is semantic and behavioural: filters always receive and must return a value.

Basic Filter Example

PHP — Filter Example
// Modify the excerpt length (default is 55 words)
add_filter( 'excerpt_length', 'my_excerpt_length' );

function my_excerpt_length( $length ) {
    return 30; // Return 30 words instead of 55
}

Filter with Multiple Arguments

PHP — Filter with Custom Output
// Modify how WordPress generates excerpt "read more" links
add_filter( 'excerpt_more', 'my_excerpt_more' );

function my_excerpt_more( $more_string ) {
    return ' Continue reading →';
}
Critical reminder: Always return something from a filter. Returning nothing (null) replaces the value with null — breaking the system.

Creating Your Own Filters

Make your plugin's values filterable — letting other code customise your output:

PHP — Custom Filter Hook
function my_plugin_get_greeting( $name ) {
    $greeting = "Hello, {$name}!";

    // Allow other code to modify the greeting
    return apply_filters( 'my_plugin_greeting', $greeting, $name );
}

Users of your plugin can customise the greeting:

PHP — Filtering a Custom Hook
add_filter( 'my_plugin_greeting', function( $greeting, $name ) {
    return "Namaste, {$name}!"; // Localised greeting
}, 10, 2 );

Priority: Controlling Execution Order

When multiple functions hook into the same action or filter, priority determines the order:

PHP — Hook Priority
// These run in order: 5 → 10 (default) → 20
add_action( 'init', 'run_first',  5  );
add_action( 'init', 'run_second', 10 );
add_action( 'init', 'run_third', 20 );

Lower numbers run first. Same priority runs in registration order.

Common use cases for priority:

  • Run before a specific plugin (use a lower number than the plugin's priority)
  • Run after everything else (use a high number like 99 or 999)
  • Ensure setup happens before functionality (e.g., register post types at init priority 10, then register REST API routes at priority 20)
03
Object-Oriented Hooks

In OOP-based plugins and themes, hooks use class methods as callbacks:

PHP — OOP Hooks
class My_Plugin {
    public function __construct() {
        // Hook using array syntax: [instance, method_name]
        add_action( 'init', array( $this, 'initialise' ) );
        add_filter( 'the_content', array( $this, 'modify_content' ) );

        // Static method
        add_action( 'admin_init', array( 'My_Plugin', 'admin_setup' ) );
    }

    public function initialise() {
        // Instance method called when 'init' fires
    }

    public function modify_content( $content ) {
        // Modify and return
        return $content . '<p>Added by My Plugin</p>';
    }

    public static function admin_setup() {
        // Static method
    }
}

// Instantiate — hooks are registered in __construct
new My_Plugin();

To remove an OOP hook, you need a reference to the original object:

PHP — Remove OOP Hook
$plugin_instance = new My_Plugin();
// Later...
remove_action( 'init', array( $plugin_instance, 'initialise' ) );

Essential WordPress Action Hooks Reference

Hook When It Fires
muplugins_loadedMust-use plugins loaded
plugins_loadedAll plugins loaded
setup_themeTheme setup begins
after_setup_themeTheme setup complete
initBasic WordPress setup complete, before headers
wp_loadedEverything loaded
wpWordPress query set up
template_redirectBefore template file is loaded (use for redirects)
wp_enqueue_scriptsEnqueue front-end scripts/styles
wp_headInside <head> tag
wp_footerBefore closing </body>
admin_initAdmin area initialised
admin_menuAdmin menus registered
admin_enqueue_scriptsEnqueue admin scripts/styles
save_postPost saved to database
publish_postPost published
pre_get_postsBefore WP_Query executes
widgets_initRegister sidebars/widget areas

Essential WordPress Filter Hooks Reference

authenticate
Filter What It Filters
the_contentPost content before display
the_titlePost title
the_excerptPost excerpt
excerpt_lengthAuto-excerpt word count
excerpt_more"Read more" text after excerpt
wp_title<title> tag content
body_classBody element CSS classes
post_classPost wrapper CSS classes
upload_mimesAllowed upload file types
wp_mailEmail arguments before sending
login_redirectWhere to redirect after login
Authentication process
query_varsURL query variables
pre_get_postsWP_Query arguments (works as action too)

Common Hook Patterns and Mistakes

Late Hook Registration

Some hooks fire very early — if you call add_action after the hook has already fired, your callback never runs:

PHP — Correct Late Registration
// WRONG - 'init' has already fired by the time this executes if added too late
// Right approach: always hook everything from your main plugin file
add_action( 'plugins_loaded', function() {
    add_action( 'init', 'my_function' ); // This works
});
Forgetting to Return in Filters
PHP — The Mistake
// WRONG - returns null, breaks the content
add_filter( 'the_content', function( $content ) {
    $content .= '<p>Added text</p>';
    // Forgot return!
});

// CORRECT
add_filter( 'the_content', function( $content ) {
    $content .= '<p>Added text</p>';
    return $content; // Always return
});
Anonymous Functions and Remove

Anonymous functions (closures) can't be removed because you have no reference to them:

PHP — Anonymous Function Problem
// WRONG - can't remove this later
add_action( 'init', function() { /* ... */ } );

// RIGHT - named function is removable
add_action( 'init', 'my_named_function' );
function my_named_function() { /* ... */ }
remove_action( 'init', 'my_named_function' );
Pro Tip: Use named functions for any hook registration you might need to remove later. This is a standard WordPress development practice.

Frequently Asked Questions

Q: What's the difference between `do_action()` and `apply_filters()`?
A: do_action() fires an action hook — runs callbacks without expecting a return value. apply_filters() fires a filter hook — runs callbacks and passes a value through them, expecting the final modified value to be returned.
Q: How do I find what hooks are available in a plugin or theme?
A: Use the Query Monitor plugin — it shows all hooks that fired on a page, what callbacks are attached, their priorities, and execution times. Alternatively, search the plugin/theme code for do_action and apply_filters calls to see exactly what hooks are available.
Q: Can I hook into hooks that fire inside another plugin?
A: Yes, if that plugin uses do_action() or apply_filters(). Well-designed plugins expose hooks at key points specifically to allow this kind of extension. This is what makes the WordPress ecosystem so powerful — plugins can extend each other without modifying each other's code.
Q: What happens if two plugins hook into the same hook with the same priority?
A: Both callbacks run in the order they were registered. If both use the default priority of 10, the one registered first runs first. If you need your code to run before another plugin's, use a lower priority number (e.g., 9 instead of 10).
Q: Can I hook into the same hook multiple times?
A: Yes, absolutely. This is standard practice. For example, five different plugins can all hook into the_content to add their own modifications. WordPress runs them all in priority order, and each modification is applied sequentially. This is how multiple plugins can coexist without conflict.
Q: Do hooks run on every page load?
A: It depends on the hook. Hooks like init and wp_enqueue_scripts run on every page load. Hooks like save_post and publish_post only run when a post is saved or published. Front-end hooks (wp_head, wp_footer) run on every front-end page load. Admin hooks (admin_init) only run in the admin area.

Final Thoughts

Actions and filters are the vocabulary of WordPress development. Master them and you can modify or extend virtually any behaviour in WordPress without touching core code — creating maintainable, upgrade-safe customisations that work correctly alongside other plugins and themes.

Study the hooks that fire during the WordPress execution sequence. Use Query Monitor to discover hooks in third-party code. Build your own hookable APIs in your plugins. And always, always return values from filter callbacks.

Need help building custom WordPress plugins with clean hook architecture? Our development team writes well-architected, extensible plugins that follow WordPress best practices.

Contact us today and we'll sort it out.
Views: 108