Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
duplicate of Why does save_post action fire when creating a new post? –  Milo Oct 29 '13 at 2:20
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks I ended up checking if the post_status was publish –  Anagio Oct 29 '13 at 8:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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