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:
- Hook into `save_post`
- Use the given `$post_id` to modify the post
- Update the post
- 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
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.