Tag Archives: PSA

PSA: Don’t (necessarily) Trigger a Save from a Save in WordPress

I know what you’re thinking. John got caught in an endless loop, and now he’s sharing his stupidity with us.

Good guess. Normally you’d be right. This is not the case this time, though.

Say you need to process some data and it takes a while. Normally you’d render the data in a shortcode, but you don’t want to run all that churn on the front end while your readers are waiting. Makes sense to process the data and inject it on save so it’s just in the content, right?

Yeah, actually! That’s a great idea!

Maybe something like this?

NOOOOOOO. Don’t do that. I see you, thinking you’re clever, removing the function from its hook and re-adding it. Well your function might not be the only one hooked into a save. Now what do you think about that, huh? Not so smart, now, are we?

What you want is the wp_insert_post_data filter:

wp_insert_post_data runs before the database is updated and lets you modify post data before the update or insert happens. It has an optional 2nd argument containing the old post data as well, so you can check what’s been updated too, if necessary.