DEV Community

Abdeldjalil
Abdeldjalil

Posted on

1

How to Prevent Infinite Loops in `save_post` Hook in WordPress

When you use the save_post hook, you may run into an infinite loop issue. This happens when you try to update the post inside the save_post action, which re-triggers the hook endlessly.

To solve this:

  1. Hook into save_post: Add your custom function to save the post.
  2. Remove the Hook Before Updating: Before calling wp_update_post(), temporarily unhook your function to stop it from firing again.
  3. Re-hook After Update: Once the update is done, reattach the hook.

Final Example:

function your_custom_save_function($post_id) {
    // Ensure this only runs once by unhooking
    remove_action('save_post', 'your_custom_save_function');

    // Update the post without triggering the save_post hook again
    wp_update_post(array(
        'ID' => $post_id,
        'post_title' => 'Updated Title',
    ));

    // Re-hook the save_post action to handle future saves
    add_action('save_post', 'your_custom_save_function');
}

// Hook into save_post
add_action('save_post', 'your_custom_save_function');
Enter fullscreen mode Exit fullscreen mode

This way, you prevent the infinite loop and ensure your updates go through smoothly.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more