☰
WORDPRESS / PRACTICE

How to Prevent Recursion in save_post in WordPress

How to Prevent Recursion in save_post in WordPress

The save_post hook is useful for synchronizing custom fields, taxonomies, prices, external IDs, and other data when a post is saved. The problem occurs when the callback modifies that same post and triggers the save process again.

The most common scenario is calling wp_update_post() inside save_post. WordPress runs the update process again, calls save_post again, and repeats the callback until the site encounters duplicate requests, a hang, or an Allowed memory size exhausted error. The practical approach below shows how to protect this code.

Why save_post Can Run More Than Once

save_post fires after a post is saved. If the callback calls wp_update_post(), WordPress runs through the update process again and may trigger the same hook repeatedly. If the callback is attached to save_post without limiting the post type, it may also respond to posts that are irrelevant to the logic.

It is important to distinguish between operations. update_post_meta() usually does not trigger save_post, but it does trigger its own metadata hooks, such as update_post_meta or updated_post_meta. If other code listens to those events and updates the post again, an indirect loop is still possible. wp_update_post() directly changes the post and is the main source of repeated save_post execution.

  • wp_update_post() is called inside a save_post callback;
  • the post is saved again by an import, the REST API, or another plugin;
  • revisions and autosaves are processed as ordinary posts;
  • there is no check to determine whether the new value actually differs from the old one.

Basic Checks Before Running the Callback

Before running the main logic, exclude WordPress's technical save operations. Revisions and autosaves can cause additional executions that should not start synchronization of the primary data.

You should also check the user's capabilities. Data from $_POST must not be considered trusted simply because the callback runs during a save. For an admin-area form, add a nonce check if your form provides one.

  • Check wp_is_post_revision($post_id).
  • Check wp_is_post_autosave($post_id).
  • Account for DOING_AUTOSAVE, but do not rely on this constant alone.
  • Limit the callback to the required post type, for example save_post_product.
  • Check current_user_can('edit_post', $post_id) when the operation runs in a user context.
  • For a custom form, verify the nonce before reading its fields.

Use an Execution Flag to Prevent Recursion

For a simple callback, a local execution flag is sufficient. A static variable retains its value when the same callback is entered again during the current request. The first call sets the flag to true, while a repeated call exits immediately.

The example below uses save_post_product, so the code responds only to product posts. The form value is unslashed and sanitized before saving, and an empty value is not stored.

  • Set the flag before performing actions that could trigger the callback again.
  • Set it back to false after the operation completes.
  • Do not use a global variable when a static variable inside the specific callback is sufficient.
add_action('save_post_product', function ($post_id, $post, $update) {
    static $running = false;

    if (
        $running
        || wp_is_post_revision($post_id)
        || wp_is_post_autosave($post_id)
        || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    ) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (isset($_POST['my_form_nonce'])
        && !wp_verify_nonce($_POST['my_form_nonce'], 'my_form_action')) {
        return;
    }

    $running = true;

    $value = sanitize_text_field(wp_unslash($_POST['source_id'] ?? ''));
    if ($value !== '') {
        update_post_meta($post_id, '_source_id', $value);
    }

    $running = false;
}, 10, 3);

Compare the Old and New Values

Recursion protection does not replace data validation. Even when a repeated call does not create a loop, the post may still be updated unnecessarily and metadata hooks may run many times.

Before calling update_post_meta(), retrieve the current value with get_post_meta() and write the value only when it has actually changed. This reduces the number of operations and makes debugging easier.

  • Define the value format before comparing it: string, number, array, or JSON.
  • For arrays, normalize their order and structure before comparison.
  • Do not confuse a missing meta field with an empty string if they represent different business states.
  • If the field must be removed when its value is empty, explicitly use delete_post_meta().
$new_value = sanitize_text_field(wp_unslash($_POST['source_id'] ?? ''));
$old_value = (string) get_post_meta($post_id, '_source_id', true);

if ($new_value !== $old_value) {
    if ($new_value === '') {
        delete_post_meta($post_id, '_source_id');
    } else {
        update_post_meta($post_id, '_source_id', $new_value);
    }
}

How to Safely Call wp_update_post() in save_post

If you need to change the post itself—for example, its title, status, or slug—updating metadata is not enough. In this situation, use one of two approaches: a recursion flag or temporarily removing the specific callback.

remove_action() works reliably when the callback has a stable identifier, such as a named function or an object with an accessible reference. An anonymous function declared without storing its instance cannot be removed in the same way.

  • Remove exactly the callback that calls wp_update_post().
  • Always attach the callback again after the operation.
  • Check that the new data differs from the current data.
  • Do not call wp_update_post() unnecessarily when updating only a meta field is sufficient.
add_action('save_post_product', 'sync_product_title', 10, 3);

function sync_product_title($post_id, $post, $update) {
    if (
        wp_is_post_revision($post_id)
        || wp_is_post_autosave($post_id)
        || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
    ) {
        return;
    }

    $new_title = get_post_meta($post_id, '_generated_title', true);
    if ($new_title === '' || $new_title === $post->post_title) {
        return;
    }

    remove_action('save_post_product', 'sync_product_title', 10);

    wp_update_post([
        'ID' => $post_id,
        'post_title' => $new_title,
    ]);

    add_action('save_post_product', 'sync_product_title', 10, 3);
}

Common Mistakes When Protecting save_post

Even a correctly written guard may not solve the problem if the loop is started by another callback or hook. Review the entire chain: save_post, metadata hooks, status transitions, API synchronization, and import code.

Also account for contexts where ordinary $_POST data is not available, including the REST API, WP-CLI, background tasks, and automated imports. Logic that unconditionally expects a form field may overwrite data with an empty value in these scenarios.

  • Do not use $_POST without wp_unslash() and sanitization.
  • Do not assume that update_post_meta() is completely isolated from loops: its metadata hooks may trigger other code.
  • Do not rely only on is_admin(), because an admin context does not mean that this is the required form.
  • Do not leave the execution flag set to true after an error or early exit.
  • Do not remove every save_post callback—remove only your own handler.

How to Verify That Recursion Has Been Removed

Test the callback in several scenarios: manually editing a post, autosaving, creating a revision, updating without changing any data, making a REST request, and running an import. In each case, check how many times the callback runs and which values it writes.

For diagnostics, temporarily log the post ID, post type, update value, and execution flag. Do not log large $_POST arrays or confidential data in production.

  • Make sure revisions and autosaves do not modify the primary post.
  • Check that a repeated call exits before wp_update_post() or the update procedure.
  • Check for duplicate metadata and unnecessary external requests.
  • Remove diagnostic logging after testing or restrict it appropriately.
error_log(sprintf(
    'save_post_product: ID=%d, update=%s, running=%s',
    $post_id,
    $update ? 'yes' : 'no',
    $running ? 'yes' : 'no'
));

Frequently asked questions

Does update_post_meta() trigger the save_post hook?

update_post_meta() does not usually trigger save_post directly. It triggers metadata hooks, and code attached to those hooks may indirectly call a post update or perform other operations. You should therefore analyze the entire callback chain.

Is static $running enough to prevent recursion?

For one callback during the current PHP request, it is usually enough. However, if the loop passes through another hook or callback, you need additional checks, value comparisons, or temporary remove_action().

Do you always need to use remove_action() before wp_update_post()?

No. If the callback has a recursion flag and exits correctly when called again, that may be sufficient. remove_action() is useful in more complex scenarios when you need to guarantee that a specific handler does not run during the internal update.

Why should a callback not rely only on $_POST?

save_post can run not only when a standard admin form is submitted, but also through the REST API, WP-CLI, an import, or a programmatic update. In these contexts, the expected $_POST field may not exist, so you must check for it and identify the data source.

Conclusion

Protecting save_post from recursion requires several layers rather than a single check: limit the post type, skip revisions and autosaves, verify capabilities, sanitize input, use an execution flag, and compare old and new values.

If the callback changes the post itself through wp_update_post(), use a stably identified callback and, when necessary, temporarily remove it with remove_action(). This approach prevents infinite loops while also reducing unnecessary operations during saving.

← All WordPress materials