Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 68 ยท Hooks: Actions and Filters

Core Hooks You Will Use

A guided tour of the WordPress hooks you will use daily - init, after_setup_theme, wp_enqueue_scripts, admin_menu, save_post, the_content, pre_get_posts and more - in firing order.

WordPress fires hundreds of hooks, but day-to-day development uses a small group of them again and again. Knowing what each one is for, and roughly when it fires, tells you where to put your code. Register a post type too late and its URLs 404; enqueue a script on the wrong hook and it never loads; change a query in the wrong place and the admin list breaks.

This lesson walks through the core hooks you will meet most, in the order they fire during a front-end page view, and then looks at the one with the most traps: save_post. The runnable examples replay a simulated page build with our own hook stand-in, so you can see the order. The WordPress code is read-only, and the simulated sequence is deliberately simplified: a real request fires many more hooks than we list.

You already know how hooks work from Actions and Filters and Priorities, Order and Removing Hooks. For the bigger picture of a request, see How WordPress Handles a Request.

The hooks, one by one

plugins_loaded

Fires after every active plugin file has been included. It is the earliest point where you can safely rely on other plugins' functions and classes existing, so it is the usual place to boot an object-oriented plugin or to load translations in older code.

after_setup_theme

Fires after the active theme's functions.php has loaded. This is where themes call add_theme_support(), register_nav_menus() and add_image_size(). Do not wait for init for these: some features are read earlier.

PHP
add_action( 'after_setup_theme', 'mytheme_setup' );

function mytheme_setup(): void {
    add_theme_support( 'title-tag' );
    add_theme_support( 'post-thumbnails' );
    register_nav_menus( array( 'primary' => __( 'Primary menu', 'mytheme' ) ) );
}

init

Fires once WordPress has loaded and the current user is known, but before any headers are sent. It is the home of registration code: custom post types, taxonomies, shortcodes, rewrite rules and anything that must exist before the request is parsed.

PHP
add_action( 'init', 'myplugin_register_types' );

wp_loaded and parse_request

wp_loaded fires when core, plugins and the theme are all ready, just before the request is parsed. After it, parse_request turns the URL into query variables, then the main query runs.

pre_get_posts

An action that fires before a WP_Query object runs its database query, passing the query object itself. It is the supported way to change the main query, for instance to show more posts per page on an archive. Always check $query->is_main_query() and ! is_admin() first, or you will change every query on the site, including the admin screens. The Main Query and pre_get_posts covers this in depth.

template_redirect

Fires after the main query ran and before WordPress picks a template. If you need to redirect visitors based on the request (for example, send logged-out users away from a members page), do it here, call wp_safe_redirect() and exit. Nothing has been output yet, so redirects still work.

wp_enqueue_scripts

The hook for adding front-end styles and scripts with wp_enqueue_style() and wp_enqueue_script(). WordPress runs it while building the page head. The matching hook for the admin is admin_enqueue_scripts, and for the login screen login_enqueue_scripts. See Enqueuing Styles and Scripts.

the_content

A filter, not an action. It receives the post content as a string and returns the final HTML. WordPress itself attaches several callbacks to it (block rendering, wpautop, shortcode processing and others). Your callback should return the content unchanged when it does not apply: it runs for every call to the_content(), including excerpts and widgets.

PHP
add_filter( 'the_content', 'myplugin_add_reading_time' );

function myplugin_add_reading_time( string $content ): string {
    if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
        return $content;
    }
    $minutes = max( 1, (int) round( str_word_count( wp_strip_all_tags( $content ) ) / 200 ) );
    return '<p class="reading-time">' . esc_html( $minutes ) . ' min read</p>' . $content;
}

wp_head and wp_footer

Fire inside the page's <head> and just before </body>. Themes must call wp_head() and wp_footer() in their templates (classic themes) for plugins to work. Use them for markup that cannot be enqueued, such as a tracking <meta> tag or a small footer element, and prefer enqueuing for files.

shutdown

Fires when PHP is shutting down, after the page has been generated. Rarely needed; it is useful for logging.

admin_menu and admin_init

In wp-admin, admin_menu is where you call add_menu_page() and add_submenu_page(). admin_init runs on every admin request early on; it is the place for register_setting() and for admin-side redirects. Remember that admin_init also fires for AJAX requests that go through admin-ajax.php, so guard any code that should only run on a visible admin page.

rest_api_init

Fires when the REST API server is being set up for a request. Register your routes with register_rest_route() inside a callback hooked here. Registering earlier is too soon, and registering on init runs the code on every request even when no REST call is made.

PHP
add_action( 'rest_api_init', function (): void {
    register_rest_route( 'acme/v1', '/ping', array(
        'methods'             => 'GET',
        'callback'            => fn () => array( 'pong' => true ),
        'permission_callback' => '__return_true',
    ) );
} );

Order cheat table

This table lists the hooks of a typical front-end request in the order they fire. WordPress fires others between them; the relative order of the ones shown is what matters.

Order Hook Type Typical use
1 muplugins_loaded action Must-use plugin setup
2 plugins_loaded action Boot plugins
3 after_setup_theme action Theme supports, menus, image sizes
4 init action Register post types, taxonomies, shortcodes
5 wp_loaded action Everything is ready
6 parse_request action Inspect or alter parsed request
7 pre_get_posts action Change the main query
8 wp action Main query done, $post known
9 template_redirect action Redirects before output
10 wp_enqueue_scripts action Enqueue front-end assets
11 wp_head action Output in <head>
12 the_content filter Change post content (per post)
13 wp_footer action Output before </body>
14 shutdown action Final cleanup

In wp-admin the sequence is different: admin_menu fires before admin_init. REST requests fire rest_api_init instead of the template hooks.

flowchart TD
    A["plugins_loaded"] --> B["after_setup_theme"]
    B --> C["init"]
    C --> D["wp_loaded"]
    D --> E["pre_get_posts<br/>main query"]
    E --> F["template_redirect"]
    F --> G["wp_enqueue_scripts<br/>wp_head"]
    G --> H["the_content<br/>per post in the loop"]
    H --> I["wp_footer"]
    I --> J["shutdown"]

A simplified front-end timeline. Register things early, change queries before they run, output late.

Replay a page build

The example below fires the stand-in hooks in this order and lets a pretend core, plugin and theme react at each step. Watch how the plugin's pre_get_posts callback receives the query object and changes it, and how the the_content filter runs once per post.

PHP Replaying hooks in core order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

save_post: the hook with the most traps

save_post fires whenever a post is created or updated through wp_insert_post(), which includes the classic editor, the block editor, quick edit, imports and programmatic updates. Its callback receives $post_id, $post and $update (true when the post already existed), so register it with accepted_args set to 3. There is also a more specific save_post_{$post_type} hook, such as save_post_book, which runs first and saves you a type check.

Real-world callbacks need guards, because save_post also fires for:

  • autosaves (a background draft save), which have no nonce or form data,
  • revisions, each of which is stored as a post,
  • other post types than the one you care about,
  • and users who lack permission to edit the post.

Another trap is recursion. If your callback calls wp_update_post() it triggers save_post again, forever. The usual cure is to remove your own callback, update, and add it back. If you only want to change what is being saved, the filter wp_insert_post_data is the better tool, because it changes the data before it is written and does not trigger a second save.

PHP A save_post flow with guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The page title was cleaned by the filter alone and never touched by the action, because the action ignores non-books. Both the insert and the update of the book end up with the (book) label exactly once: without the remove-and-add-back guard, the callback's own wp_update_post() call would run the callback again and again.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should you register a custom post type?

    Registration code belongs on init: it runs on every request, after WordPress is loaded and before the request is parsed, so rewrite rules and queries can see the post type.
  2. 2. What is the best hook for adding front-end stylesheets with wp_enqueue_style()?

    wp_enqueue_scripts is the hook WordPress fires for front-end assets. Enqueuing elsewhere may be too early, too late or on the wrong side (admin) of the site.
  3. 3. Your pre_get_posts callback should only change the home page's main query. Which check is essential?

    pre_get_posts fires for every WP_Query, including secondary queries and admin screens. Checking is_main_query() and is_admin() limits your change to the front-end main query.
  4. 4. A save_post callback calls wp_update_post() on the same post. What happens if you add no guard?

    wp_update_post() fires save_post again. Remove your callback before updating and add it back afterward, or use the wp_insert_post_data filter to change data before it is saved.
  5. 5. Which of these is a filter rather than an action?

    the_content receives the post content and must return the modified HTML. The other hooks are actions that run code at a moment in time and return nothing.

Summary

  • plugins_loaded boots plugins, after_setup_theme configures themes, and init registers post types, taxonomies and shortcodes.
  • pre_get_posts changes queries before they run: check is_main_query() and ! is_admin().
  • template_redirect is the place for redirects; wp_enqueue_scripts loads front-end assets; wp_head and wp_footer print into the page.
  • the_content is a filter that must always return a string, and should leave content alone when it does not apply.
  • admin_menu adds admin pages, admin_init registers settings, and rest_api_init is where REST routes belong.
  • save_post receives three arguments and fires for autosaves, revisions and every post type, so guard it and avoid recursion.

Next, move from hooks to themes: Block Themes: The Big Picture.