5

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?

3 Answers 3

7

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.

1
  • 1
    I will just jump in the comments, as i've done quite a bit of research on this too. Your method in some cases might not work. eg: If the processing begins at the end of a given second, the post_date_gmt and the post_modified_gmt will be different. you can read more on this here wordpress.stackexchange.com/a/177670/190376 Commented Jan 7, 2021 at 11:20
1

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.

0

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.

2
  • 2
    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 Commented May 6, 2016 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. Commented May 6, 2016 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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