1

I'm struggling to figure out to get the code to update a single current user meta. For instance if I want to update their first name automatically. I'm using

$current_user = wp_get_current_user(); 

to call the current user data rather than specifying a particular user ID.

2

One of two functions you'll need; update_user_meta or add_user_meta - more often than not you'll just need the former, but it's worth noting the difference:

add_post_meta will only create an entry if the $unique parameter is false, or if there is no existing data for $meta_key. update_post_meta will add if no data exists yet, otherwise it will update, depending on if/what you specified for $prev_value.

Both functions take the same three initial parameters; a user ID, a meta key, and a value:

$current_user = wp_get_current_user();
$current_user->ID; // The current user ID
$current_user_id = get_current_user_id(); // Alternative for getting current user ID

// Update current user's first name
update_user_meta( $current_user_id, 'first_name', 'Jimbo' );

// Update a specific user's first name
update_user_meta( 4 /* User ID 4 */, 'first_name', 'Janey' );
  • Thanks for this works great - just one more question, if the meta was numerical (eg Age) and I wanted to increase by 1 what would insert in here? – Garland Oct 23 '15 at 11:57
  • Get the value with get_user_meta( $id, 'age' ), increment by 1 (or set it to 1 if it's currently null), then update. – TheDeadMedic Oct 23 '15 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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