I’m trying to update a posts meta only after it has been saved or updated.
My function is pretty simple
function update_test( $post_id ) {
update_post_meta($post_id, 'copied', '1');
update_post_meta($post_id, 'blurb', 'this value updated by save_post action');
}
add_action( 'save_post', 'update_test');
When I add a new post at wp-admin/post-new.php
I can see the two custom fields values have already been updated. The fields themselves exist with Advanced Custom Fields. But shouldn’t be updated until after the post has been published / saved and or updated. Why is this updating the fields as soon as the post-new.php form loads?
1 Answer
A draft or “blank” is saved as soon as you start to create a new post. Those new posts have the post_status
of auto-draft
. Check for that to prevent your callback from firing on those “blank” post saves.
function update_test( $post_id, $post ) {
if (isset($post->post_status) && 'auto-draft' == $post->post_status) {
return;
}
update_post_meta($post_id, 'copied', '1');
update_post_meta($post_id, 'blurb', 'this value updated by save_post action');
}
add_action( 'save_post', 'update_test', 1, 2);
You may also want to check for the DOING_AJAX
and DOING_AUTOSAVE
constants.