AdvancedLesson 22 of 305 min read

Hooks: actions and filters

Understand actions and filters, priorities, conditional checks and safe hook code, with real hook runs, and learn to extend WordPress without touching the core.

In this lesson you will

  • Tell actions from filters
  • Use priorities
  • Write careful filters
  • Place hook code safely

About 17 minutes

The door WordPress leaves open

Daniel wants every post to end with ‘Thanks for reading!’ and wants a short notice sent to him whenever a post is published. He could edit WordPress files, but an update would erase his changes. Fortunately WordPress is full of hooks: named points where your code can plug in without touching the core. Almost every plugin and theme feature is built on them. Learning hooks is what separates a site owner from a WordPress developer.

Two kinds of hook

Hook What it does
Action Runs your code at a moment (‘a post was published’)
Filter Receives a value, changes it and passes it on

An action says ‘something happened, do something’. A filter says ‘here is a value, you may change it, but you must return it’. Forgetting to return the value in a filter is the most common beginner bug; the value then becomes empty and content disappears.

Hooks, run for real

A test script made up its own hook names, attached code at different priorities, fired them, removed one and finally attached a filter to the real content filter. The output is real:

action order: B (priority 5) -> A (priority 10) -> C (priority 20)
times fired: 1
filter chain 19.99 -> 24
filter with a function name: HELLO
has_action before remove: yes | after: no
the_content filter chain output: <p>Hello</p>
after our filter: <p>Hello</p><p>Thanks for reading!</p>
hooks registered on this site (count > 100): yes

Study the first line. Code with a lower priority number runs first, so priority 5 ran before 10 and 20. The default is 10. The filter chain turned 19.99 into 24: first the price was multiplied by 1.2 (23.988), then a second filter at priority 20 rounded it to one decimal. Even a plain function name such as strtoupper works as a filter. The last lines show the real content filter: our filter added a line to the end of every post’s content.

The code behind the idea

add_filter('the_content', function ($content) {
    if (is_single() && in_the_loop() && is_main_query()) {
        return $content . '<p>Thanks for reading!</p>';
    }
    return $content;
});

Notice the checks. Without them the filter would add the line to every list, widget and excerpt. A careful hook limits its effect to the place you mean. Notice, too, that the function always returns something.

Finding the right hook

  • Search the official developer reference for the hook you want.
  • Common actions: init, wp_enqueue_scripts, save_post, admin_menu, wp_footer.
  • Common filters: the_content, the_title, excerpt_length, upload_mimes.
  • Plugins document their own hooks; look for ‘developer docs’.
  • Tools exist that list the hooks that fire on a page; use one on a practice site.

Writing hook code safely

  • Put it in a small plugin or a child theme’s functions.php, never in WordPress core.
  • Prefix your function names (for example mysite_) so they cannot clash with others.
  • Keep each hook callback short and focused.
  • Check conditions (is this the right page, post type or user?) before acting.
  • Remove a hook with the same name and priority that you added it with.

Debugging hooks

If your code does nothing, ask three questions. Was the file loaded at all? Does the hook name match exactly? Is another hook running later and overwriting your change? Turn on debug logging on a practice site (WP_DEBUG and its log option), add a log line to your callback and watch the log. Remove debugging before going live.

Practice

In a small plugin or child theme, write a filter that adds a line after single posts only. Then write an action on wp_footer that prints a small copyright line. Test on a post, a page and the home page, and confirm that only the intended places change.

Practice answer

If the line shows everywhere, add the conditional checks. If it shows nowhere, check that the function returns the content and that the code file is active. Test with the debug log on.

Common mistake

Forgetting to return the value in a filter. The post body becomes empty and the site seems broken.

Real examples of useful hooks

Goal Hook idea
Add a line after each post the_content filter
Shorten excerpts excerpt_length filter
Add a tracking snippet wp_head or wp_footer action
Email yourself on publish publish_post or transition_post_status action
Add a custom file type to uploads upload_mimes filter

Each of these is only a few lines long. The skill lies in choosing the right hook, limiting the effect with conditions and testing on a practice site. Keep a personal notebook of the hooks you use, with a sentence about when each is right. After a year you will have a small library that makes every new project faster.

Hooks and performance

Hooks run on every page load that triggers them. A slow callback on a hook that fires on every request slows the whole site. Keep callbacks light, avoid database queries inside frequently-fired hooks, and cache the results of expensive work, as the performance lesson later in this course shows.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is an action hook?

  1. A type of image
  2. A point where code runs when something happens
  3. A password
  4. A menu

Filters change values instead.

Which priority runs first?

  1. Higher numbers
  2. Random
  3. Lower numbers
  4. Always 10

In the real test, 5 ran before 10 and 20.

What must a filter always do?

  1. Return a value
  2. Delete a post
  3. Print an error
  4. Reload the page

Otherwise content can disappear.

Why prefix your function names?

  1. To make them faster
  2. To hide them
  3. To avoid clashes with other code
  4. To save space

Use a unique prefix like mysite_.

Where should hook code live?

  1. A small plugin or child theme
  2. WordPress core files
  3. The media library
  4. A comment

Core edits are erased by updates.

Summary

  • Actions run code at a moment; filters change a value.
  • Lower priority numbers run first.
  • A filter must return a value.
  • Hook code goes in a plugin or child theme.

Next lesson

Next: building a small plugin of your own.

Questions

Where do I find all hooks?

The official developer reference lists core hooks. Plugins list theirs in their own documentation.

Can a hook break my site?

Yes, a mistake can cause a white screen. Test on a practice site and keep a backup.

Do I need to know PHP?

A little. You can copy patterns, but understanding what each line does keeps you safe.

Progress is saved in this browser.