WordPress save_post Gotchas

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.

One response to “WordPress save_post Gotchas”

  1. Hi, this is a comment.
    To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
    Commenter avatars come from Gravatar.

Leave a Reply

Your email address will not be published. Required fields are marked *