WordPress save_post Gotchas

Warning
This blog post is included for archival purposes and may contain outdated information. While it provides historical insights, we strongly recommend that you double-check the details before relying on any of the information outlined here.

We have taken on the task to do heavy refactoring on a client’s website that is used to handle volunteers, applicants, and relationships between them. This is incredibly challenging, but fun nonetheless.

Today I was in the process of writing an action that would do something when a new relationship was created. The relationship is a custom post type of ‘mentorship’.

After visiting the codex, it became clear that save_post_{$post->post_type} was the action to hook onto.

When defining 3 parameters for the callback function, you get the following:

function call_back_function( $post_id, $post, $update )

That last parameter, $update, is as unreliable as it can get, so please never use it.

After setting the hook I noticed that the action was called immediately when the post was created, in draft mode. This was not what I wanted, I wanted the action to fire off after the user modified things and clicked on the Publish button.

Eventually the following code did the trick – it will only fire when the user clicks the Publish button:

		if ( 'auto-draft' === $post->post_status ||
			wp_is_post_revision( $post_id ) ||
			wp_is_post_autosave( $post_id ) ) {
			return;

One would thing that just using wp_is_post_revision and wp_is_post_autosave would suffice, but in my case I had to explicitly check for auto-draft in order to avoid calling the code that has to run when the user publishes the new post.

About Author

Christian Saborio

Christian is a seasoned computer engineer with a rich career spanning collaborations with industry leaders such as Artinsoft (now Mobilize.net), Microsoft, HP, and Intel. As a technical evangelist and trainer, Christian honed his expertise in Costa Rica and Seattle, delivering impactful solutions and sharing his knowledge.

Now based in Sydney, Australia, Christian channels his passion into web development, leading a talented team to tackle diverse projects with innovation and precision. His commitment to crafting exceptional digital experiences reflects his deep-rooted enthusiasm for technology and problem-solving.

Comments

    Comments are closed

    Thank you for your interest. Please fill out this form to provide us with your contact information. We'll get back to you as soon as possible.