Avoid Loops With save_post in WordPress

When working on WordPress projects, there may be times during which you have to do some sort of processing on the content or attributes of the post before saving it to the database.

There are a number of ways to do this, but one of the most straightforward ways to go about it is to setup a custom function hooked to the save_post action and then handle the attributes of the post in that function.

If you opt to go this route, there are a few considerations that you need to make (mainly that help you avoid some type of infinite loop) in order to properly adjust the content to your liking.

save_post in WordPress

First, let’s assume that you want to modify some aspect of the post title. Perhaps you want to do something like replace one character with another character, remove any words that you deem inappropriate for a title, or so on.

Initially, it seems pretty easy to do this:

  1. Hook into save_post
  2. Use the given $post_id to modify the post
  3. Update the post
  4. Continue with WordPress’ execute

But there’s a problem here: Whenever you’re updating a post in WordPress, you’re going to likely use the wp_update_post function and in doing so you’re also going to be implicitly using the save_post hook.

Thus, this can result in an infinite loop. Fun, maybe, but no good.

So in order to fix this, you need to make sure that you remove the action, perform your work, then hook the action once again.

Here’s a quick example of how to do it:

As you can see, it’s nothing terribly complicated, but it’s something that can result in causing erradict side effects if you’re not careful or if you aren’t sure how the entire process works.

Hopefully the provided code will prevent something like this from happening in something you’re working on now, or something that you’ll be working on in the near future.

4 Replies to “Avoid Loops With save_post in WordPress”

    1. You’re right – every now and then I’m going to end up posting on things I’ve already covered.

      Sometimes, the posts are going to be exactly the same; other times, it may include subtle changes or nuances to what we’ve already got.

      Either way, that’s the nature of blogging I suppose :).

      Thanks for the comment though, Hugh, always glad to see you dropping by.

        1. The way I see it, I’m going to be learning things that I didn’t previously know before and some things are going to updated or easier for me to explain now.

          Rather than update old posts, I just assume add a new post :).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.