3

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

1 Answer 1

7

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.

2
  • Thanks I ended up checking if the post_status was publish Commented Oct 29, 2013 at 8:02
  • For whatever reason, wp_is_post_revision and wp_is_post_autosave were always false in my plugin, even when creating a new post, but this works a charm. Thanks! Commented Jun 10, 2020 at 20:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.