3

I'm trying to fire some code only when a document type is created using save_post, but $update is always true, even when first publishing it.

I assume this is because there's an autodraft created first. Is there any way around this?

5

So appreciate this is a bit late but I was having the exact same issue, the $update parameter is almost completely useless if you want to check whether it is a new post or not.

The way I got around this was to compare the $post->post_date with $post->post_modified. Full code snippet below.

add_action( 'save_post', 'save_post_callback', 10, 3 );

function save_post_callback($post_id, $post, $update) {
    $is_new = $post->post_date === $post->post_modified;
    if ( $is_new ) {
        // first publish
    } else {
        // an update
    }
}

Hope that helps anybody else finding this.

0

One approach is to use get_post_status()

According to the codex http://codex.wordpress.org/Function_Reference/get_post_status

'publish' - A published post or page
'pending' - post is pending review
'draft' - a post in draft status
'auto-draft' - a newly created post, with no content
'future' - a post to publish in the future
'private' - not visible to users who are not logged in
'inherit' - a revision. see get_children.
'trash' - post is in trashbin. added with Version 2.9.

Possibly in your code the status is auto-draft or draft. If the status is true for both, it's probably the first save. If not, it's an update.

-1

A more reliable way of checking is to get $_POST['original_publish'], as that will return 'Publish' on first publishing it, and 'Update' on updating it.

  • 1
    1. Never a good thing to rely on an obscure undocumented detail. 2. when publishing via XML-RPC, JSON API or whatever it is unlikely to work – Mark Kaplun May 6 '16 at 8:13
  • @MarkKaplun - I don't want it to work on anything other than hitting the publish button, so that's okay by me. But a good point. – SinisterBeard May 6 '16 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.