1

I want to track when a certain piece of user meta is changed in the admin, and then perform an action. I thought I found the correct hook for it (from https://codex.wordpress.org/Plugin_API/Action_Reference/profile_update), but when I use this code:

add_action( 'profile_update', 'my_profile_update', 10, 2 );

function my_profile_update( $user_id, $old_user_data ) {
    error_log(print_r($old_user_data,true));
}

My error log does not show the user meta that I am changing, only values from the main wp_users table and a bunch of capabilities. How can I grab the previously changed user_meta value (or detect a changed user_meta value) when a profile is saved in the admin?

1 Answer 1

3

I figured out the answer. I needed to use the insert_user_meta filter, not an action hook. And then I ALSO needed a combo of get_user_meta (to get the old data) and $_POST to get the value being changed to. Putting it all together, here is my final code to find when a particular user_meta field (in my case created with ACF) changes from one value to another:

add_filter( 'insert_user_meta', function( $meta, $user, $update ) {
  if( true !== $update ) return $meta; // if not an update (b/c it is a create) do nothing
if(is_admin()) { // check if we are in admin not front end
  $old_meta = get_user_meta( $user->ID );
  if( $old_meta['verified_member'][0] !== $_POST['acf']['field_5ad4eecd7564b'] ) {
    error_log("verified_member was modified from " . $old_meta['verified_member'][0] . " to " . $_POST['acf']['field_5ad4eecd7564b']);
  }}
  return $meta;
}, 10, 3 );
2
  • A better (not acf dependent) solution would be to use two different filters, one to retrieve the old value and save to a variable and the second to catch the new value and do the logic...
    – xnagyg
    May 4, 2020 at 20:41
  • In this case: update_{$meta_type}_meta and updated_{$meta_type}_meta are the actions
    – xnagyg
    May 4, 2020 at 20:47

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.