DEV Community

Abdeldjalil
Abdeldjalil

Posted on

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.

Top comments (0)