Update post meta - check if value is same as before

2.5k views Asked by At

I'm updating a post meta field and that's working for me with the code below. Now I want to upgrade the code to check if new value is same as old value

add_action( 'updated_post_meta', 'update_function', 10, 4 );
function update_function( $meta_id, $post_id, $meta_key, $meta_value )
{
    // check if $old_value == $new_value
}

Should I be using some other action hook? Where is the old value saved and where the new one?

1

There are 1 answers

2
mackelele On BEST ANSWER

In order to get the post meta value you should use get_post_meta($post_id,'meta_key',true) Read more about it here get_post_meta from WordPress docs

Then using this code inside of your function should solve your problem

// not sure if you should use this action hook, maybe try a different trigger
// if u=you are updating user meta then use user_register hook to update user after 
registration

// hook that you are using is update_post_meta and not updated_post_meta
add_action( 'updated_post_meta', 'update_function', 10, 4 );
function update_function( $meta_id, $post_id, $meta_key, $meta_value )
{
  // get post meta value
  $old_value = get_post_meta($post_id, $meta_key, true);
  if($old_value == $new_value){
    return false;
  }else{
    return $new_value = update_post_meta($post_id, $meta_key, $updated_value);
  }
}