1

I'm currently trying to update a post's meta value within the save_post action. The problem with this is that it gets overwritten immediately. I've been banging my head on this problem for several hours and can't get it to work. Is there a way to update the meta without it being overwritten?

My code is below

add_action( 'save_post_promo', 'update_promo_tag_id', 10, 1 );
function update_promo_tag_id( $post_id ) { update_field( 'one_time_tag_id', 'updated!', $post_id ); }
8
  • 1
    When you say it gets overwritten, it gets overwritten to what? What's your final post meta value?
    – nibnut
    Commented Mar 9, 2017 at 20:58
  • It's empty. There's previously no value in the field. Commented Mar 9, 2017 at 21:08
  • Ok - and you are certain the code runs at all? Do you have any other plugins or code that maybe use a filter on custom field values?
    – nibnut
    Commented Mar 9, 2017 at 21:09
  • I'm sure the code runs, if I hardcore the Post ID of a different post it runs. I have no other code that fires on save. Commented Mar 9, 2017 at 21:12
  • Weird - maybe this can help? support.advancedcustomfields.com/forums/topic/…
    – nibnut
    Commented Mar 9, 2017 at 21:14

1 Answer 1

1

The problem is probably that the $post_id parameter passed to via the save_post_$post_type hook is not the same $post_id as the original post - it's the $post_id of the temporary post that's created when you edit a post.

To confirm this:

add_filter( 'pre_post_update', 'wpse_pre_post_update', 10, 3 );
add_filter( 'save_post', 'wpse_save_post', 10, 1 );

function wpse_pre_post_update( $post_id, $post, $update ) {
  echo $post_id . '<br>';
}
function wpse_save_post( $post_id ) {
  echo $post_id;
  wp_die();
}

If you're trying to add a new post, then pre_post_update hook doesn't fire and WP will die before taking you to edit screen. Comment out the wp_die() line, then click the "Add New" link. Now, uncomment out the wp_die() and save the post. Two non-identical IDs should be output before WP dies.

The first ID is the ID of the actual post. The second ID is the ID of the temporary post.

It doesn't really make sense to me why WordPress does it this way, and I have no idea if it's always been like this. But it has this behavior for me running a fresh install of WP 4.7.3.

Unless for some reason you need to update the option after the post is saved, I'd use the pre_post_update hook instead.

add_filter( 'pre_post_update', 'update_promo_tag_id', 10, 3 );
function update_promo_tag_id( $post_id, $post, $update ) { 
  if( 'promo' !== $post->post_type ) {
    return $post_id;
  } 
  update_field( 'one_time_tag_id', 'updated!', $post_id );
  return $post_id;
}

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.