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?
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.
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
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.
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.