Question

Lets say I have custom field on post editor, and I change value from AAA to ZZZ.. :

add_action('save_post', 
   function($post){
      $value = get_post_meta($post->ID, 'mykey');

   }
, 1);

How to get the old value (AAA) of that meta-key? during save_post (even earlier 1st priority), I get ZZZ

Was it helpful?

Solution

save_post Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID and post object. Runs after the data is saved to the database.

above paragraph is quoted from WP Codex.

so you cannot use this hook to get older value because it fires after saving new values to DB. WP has another action hook named wp_insert_postbut sadly this hook does same thing as save_post

alternatively you can use Filters to get the job done. WP provides few filter to edit the post while saving or before saving to DB. like wp_insert_post_data & content_save_pre might work for you, i think.

Update

here is another discussionon this topic which might be helpful for you.

OTHER TIPS

The trick I did was:

1) Created a hidden meta box, where I inserted input, with value of current_meta_value
2) during save_post i checked it against to new_meta_value.

that was all.

This might be against the WordPress-rules or something. But I got this working:

add_action( 'save_post', 'wp258055_save_post_callback' );

function wp258055_save_post_callback( $post_id ){
  $value_in_db = get_post_meta( $post_id, 'mykey', true );
  $value_about_to_be_saved = $_POST['mykey'];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top