wp_after_insert_post vs save_post: Run Code After Meta and Terms Are Saved

wp_after_insert_post: run code after meta and terms are saved

save_post is the hook everyone knows, and in the block editor it fires too early for many tasks. The editor saves the post through the REST API, and the REST controller writes the post first and the meta fields and terms afterwards. Code on save_post then reads the old meta values. WordPress 5.6 added wp_after_insert_post for this case: it fires after the post, its terms and its meta are all saved.

Problem: A plugin sends a notification when a post is published and includes the value of a custom field and the categories. From the classic editor it works; from the block editor the email contains the values from before the save, or nothing.

Solution: Move the code from save_post to wp_after_insert_post, use its $post_before argument to detect the first publication, skip revisions and autosaves, and protect against running twice in one request.

The order of the hooks in a REST save

When the block editor saves a post, the REST posts controller does roughly this:

  • wp_insert_post() writes the post row and fires save_post_{post_type}, save_post and wp_insert_post.
  • The controller then saves the terms (categories, tags) and the meta fields registered with show_in_rest.
  • Finally it calls wp_after_insert_post(), which fires the wp_after_insert_post action.

In the classic editor, terms and meta boxes are saved inside wp_insert_post() or on save_post, so the problem does not show up there. wp_after_insert_post is the one hook that is late enough in both cases.

Notify on the first publication

add_action( 'wp_after_insert_post', 'ha_notify_on_publish', 10, 4 );
function ha_notify_on_publish( int $post_id, WP_Post $post, bool $update, ?WP_Post $post_before ): void {
    if ( 'post' !== $post->post_type || 'publish' !== $post->post_status ) {
        return;
    }
    if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
        return;
    }
    // Only the transition into "publish", not every update of a published post.
    if ( $post_before && 'publish' === $post_before->post_status ) {
        return;
    }
    if ( get_post_meta( $post_id, '_ha_notified', true ) ) {
        return;
    }
    update_post_meta( $post_id, '_ha_notified', time() );

    $source = get_post_meta( $post_id, 'ha_source', true );            // saved by the REST request
    $cats   = wp_list_pluck( get_the_category( $post_id ), 'name' );   // saved too

    wp_mail(
        get_option( 'admin_email' ),
        /* translators: %s: post title */
        sprintf( __( 'Published: %s', 'textdomain' ), wp_strip_all_tags( get_the_title( $post ) ) ),
        implode( "\n", array(
            get_permalink( $post ),
            /* translators: %s: categories */
            sprintf( __( 'Categories: %s', 'textdomain' ), implode( ', ', $cats ) ),
            /* translators: %s: source */
            sprintf( __( 'Source: %s', 'textdomain' ), $source ),
        ) )
    );
}

The arguments:

  • $update is false only when the post is created. A post written as a draft and published later is an update.
  • $post_before is the post object before the save, null for new posts. Comparing its status with the new one is the reliable way to detect “just published”.
  • The meta flag _ha_notified keeps the email from being sent twice. The block editor sends a second request after publishing when meta boxes from PHP are on the screen, and a post that is unpublished and published again should not notify a second time either.

Scheduled posts work too: when the cron publishes a future post, wp_publish_post() calls wp_after_insert_post() as well, with $post_before in status future.

Status changes without saving: transition_post_status

For reactions to the status alone, transition_post_status fires with the old and the new status, but it runs inside wp_insert_post() as well, before the REST controller saves meta and terms. It is fine for “write a log entry”, not for “read the custom fields”. The status hooks in WooCommerce follow the same idea: WooCommerce order status transitions.

Meta that must be there

Only meta keys registered for the REST API are saved by the editor in the same request:

add_action( 'init', function (): void {
    register_post_meta( 'post', 'ha_source', array(
        'type'              => 'string',
        'single'            => true,
        'show_in_rest'      => true,
        'sanitize_callback' => 'sanitize_text_field',
        'auth_callback'     => fn() => current_user_can( 'edit_posts' ),
    ) );
} );

Meta from a classic meta box is saved in a separate request after the REST save, on save_post of that request; how such a meta box is saved: a custom meta box with secure save handling.

NOTE: Changing the same post inside wp_after_insert_post with wp_update_post() fires all save hooks again, including this one. Remove the callback before the update and add it back afterwards, or write the change with update_post_meta(), which does not trigger the post save hooks. How actions and filters work in general: WordPress actions and filters.