wp_after_insert_post Is a Trigger, Not a Worker: Deferring a Broken-Link Audit

The symptom: saves get slower, and the audit still misses links

You hook a broken-internal-link check to wp_after_insert_post. Every save now waits on a loop of HTTP requests to your own permalinks. The editor spinner hangs. Then you notice the audit reports links that are fine, misses links that are broken, and runs three times for one click of Update.

The trace is not subtle. The hook fires from more than one save path, it fires for creates as well as updates, and the save path itself can be suppressed by callers. Treating it as a synchronous worker is the root cause. The fix is to treat it as a trigger: enqueue a post ID, run the audit elsewhere, store the result.

What the hook actually guarantees

The WordPress developer reference for wp_after_insert_post states that it fires once a post, its terms and meta data has been saved. It passes four arguments:

do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );

So the callback receives the post ID, the post object, a boolean indicating whether this is an update, and the prior post object — null for new posts. That is the contract. It does not promise that the post content is unchanged since the last audit, that the save came from the editor, or that the hook will fire for every write to the posts table.

That last point matters. The hook is fired by wp_insert_post, which is the function wp_update_post delegates to. The reference for wp_insert_post documents a $fire_after_hooks parameter, defaulting to true, that controls whether the after-insert hooks fire. The reference for wp_update_post shows it passing that argument straight through:

return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );

Any code that calls either function with $fire_after_hooks = false saves content without your callback running. The audit cannot assume it is the only observer of a content change.

Trace: the REST controller fires the hook itself

The block editor saves through the REST API. The source for WP_REST_Posts_Controller::update_item shows the sequence: it calls wp_update_post with the after hooks disabled, then handles format, featured media, sticky, template, terms, and meta, and only then calls the hook directly:

$post_id = wp_update_post( wp_slash( (array) $post ), true, false );
// ... terms, meta, featured media, template ...
wp_after_insert_post( $post, true, $post_before );

This is deliberate. The hook fires after the terms and meta are saved, so a callback sees the final state of the post rather than a half-written one. That is the useful guarantee. But the same controller’s create path also calls it:

wp_after_insert_post( $post, false, null );

So a callback that assumes $update === true will skip newly created posts. A callback that assumes it is running inside an editor save will be wrong for REST clients, WP-CLI imports that use wp_insert_post, and any other code path that reaches the same function.

If you want to see which routes and methods your install exposes, the REST API routes and endpoints documentation notes that the index at /wp-json/ reports the available routes, supported HTTP methods, and registered endpoints. That is a faster check than guessing from the editor’s network panel.

Root cause: the hook is a save notification, not a change event

Three properties of the hook make inline auditing fail:

  1. It fires per save, not per content change. A save that changes only the title still fires it. A save that changes nothing still fires it. The hook does not tell you what changed; $post_before lets you compare, but comparing full content on every save is work you may not need.
  2. It fires from multiple callers. The REST controller, wp_update_post, and direct wp_insert_post calls all reach it. Some callers suppress it. The callback cannot infer the user’s intent from the hook arguments alone.
  3. It runs inside the save request. Any HTTP work you do in the callback is added to the response time of the save. If the audit checks twenty internal links and each check takes a moment, the editor waits for all twenty.

The fix is architectural: the hook enqueues work, and a separate runner performs the audit. The hook’s job is to say “this post was saved”; the runner’s job is to decide whether the post needs checking and to do it outside the save request.

Fix: enqueue a post ID, dedupe, and run the audit elsewhere

The following callback does three things: it skips revisions and autosaves, it dedupes by post ID using a short-lived transient, and it schedules a single event. It does not perform any HTTP requests.

add_action( 'wp_after_insert_post', 'jv_enqueue_link_audit', 10, 4 );

function jv_enqueue_link_audit( $post_id, $post, $update, $post_before ) {
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    if ( 'auto-draft' === $post->post_status ) {
        return;
    }
    if ( ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
        return;
    }

    $lock_key = 'jv_link_audit_lock_' . $post_id;
    if ( false !== get_transient( $lock_key ) ) {
        return;
    }
    set_transient( $lock_key, 1, 5 * MINUTE_IN_SECONDS );

    if ( ! wp_next_scheduled( 'jv_run_link_audit', array( $post_id ) ) ) {
        wp_schedule_single_event( time() + 30, 'jv_run_link_audit', array( $post_id ) );
    }
}

Two details are load-bearing. The transient is a debounce, not a permanent lock: it collapses rapid successive saves into one scheduled run, and it expires so a later edit can schedule again. The wp_next_scheduled check prevents duplicate events for the same post ID. Neither is a substitute for the other; the transient handles the burst, the scheduled-event check handles the queue.

The runner is a separate callback on the custom action. It reads the post’s current stored content, extracts internal links, checks them, and stores the result. It does not call wp_update_post unless it needs to write a meta flag, and if it does, it follows the warning in the wp_update_post reference: calling wp_update_post from inside a save callback can create an infinite loop, and the documented remedy is to remove the hook before updating and re-add it afterward. The same discipline applies here — unhook the enqueue callback before any write that would fire it again.

Storing the result: post meta versus a custom table

The audit result should be stored, not recomputed on every page view. The simplest place is post meta: a key such as _jv_broken_links holding a serialized array of URL, status, and the post’s content hash at the time of the check. The wpdb class reference is the relevant primary source if you prefer a custom table; it documents the insert, update, and query methods and the requirement to escape untrusted values with prepare().

Post meta is a design choice, not documented guidance. It has one practical advantage: it travels with the post through export and import, and it is visible to any code that already reads post meta. A custom table has the advantage of indexed queries if you need to list every post with a broken link across a large install. For a small-to-mid publishing team, post meta is usually enough; the query below finds posts whose stored audit result is non-empty:

SELECT p.ID, p.post_title, pm.meta_value
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.ID
WHERE pm.meta_key = '_jv_broken_links'
  AND pm.meta_value != ''
  AND p.post_status = 'publish'
ORDER BY p.post_modified DESC;

If you store the content hash alongside the result, the runner can skip the HTTP checks when the hash matches the current content. That is the difference between an audit that runs on every save and an audit that runs when the content actually changed.

Verification: confirm the hook fired and the job ran

Query Monitor will show the hook firing on the save request and the scheduled event running on a later request. If you do not have Query Monitor, log the enqueue and the runner separately:

add_action( 'jv_run_link_audit', 'jv_run_link_audit', 10, 1 );

function jv_run_link_audit( $post_id ) {
    error_log( sprintf( 'jv_link_audit start post=%d', $post_id ) );
    // ... extract, check, store ...
    error_log( sprintf( 'jv_link_audit done post=%d', $post_id ) );
}

From WP-CLI, you can confirm the scheduled event exists and run it manually:

wp cron event list --fields=hook,next_run_relative,args
wp cron event run jv_run_link_audit --due-now

The first command should show one pending event per post ID after a burst of saves, not one per save. The second runs the due events immediately, which is useful when you have disabled WP-Cron in wp-config.php and drive it from the system scheduler. The retrieved sources do not document WP-Cron reliability or timing, so treat the scheduling interval as a tuning parameter rather than a guarantee.

What to log and what to show editors

Log the post ID, the content hash, the number of links checked, and the number of failures. Do not log the full post content. If the audit writes a meta flag, surface it in the editor as a notice or a column in the posts list; the point of storing the result is that an editor can see it without triggering a new run.

The audit should also record the URL and the HTTP status for each failure, so the editor can distinguish a 404 from a timeout from a redirect. A link that returns 200 after a redirect is not broken in the sense that matters to a reader, but it is worth knowing about. That distinction belongs in the stored result, not in the save request.

FAQ

Does wp_after_insert_post fire for block editor saves?

Yes. The REST posts controller calls it after handling terms, meta, featured media, and template, as shown in the update_item source. The block editor saves through that controller.

Why does my callback run more than once per save?

Because the hook fires from more than one path, and because a single editor action can produce more than one save request. The hook arguments do not tell you which path invoked it. Dedupe by post ID and debounce with a transient rather than trying to infer the caller.

Can I skip the audit for revisions and autosaves?

You can check wp_is_post_revision( $post_id ) and the post status in the callback, as the example above does. The retrieved sources do not document the hook’s behavior for every autosave path, so verify on your install with Query Monitor before relying on a skip rule.

Should the audit run on every save or only when content changes?

Only when content changes, if you can afford to store a content hash. The hook does not tell you what changed; comparing the stored hash to the current content is the reliable way to decide whether the HTTP checks are needed.

What if another plugin calls wp_update_post with $fire_after_hooks = false?

Your callback will not run for that save. The audit is a notification-driven process, not a guarantee that every write is observed. If you need coverage for those writes, run a periodic sweep with WP-CLI in addition to the hook-driven audit.