7

I'm trying to update multiple meta_key for user in WordPress

update_user_meta( $user_id, array( 'nickname' => $userFirstName, 'first_name' => $userFirstName, 'last_name' => $userLastName , 'city' => $userCityID , 'gender' => $userGenderID) );

but it is not working. How can we update multiple meta_key for user?

Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58
Fadi
  • 2,320
  • 8
  • 38
  • 77

3 Answers3

10

Try:

<?php
$user_id = 1234;

$metas = array( 
    'nickname'   => $userFirstName,
    'first_name' => $userFirstName, 
    'last_name'  => $userLastName ,
    'city'       => $userCityID ,
    'gender'     => $userGenderID
);

foreach($metas as $key => $value) {
    update_user_meta( $user_id, $key, $value );
}

So instead of passing your array to update_user_meta which only accepts string arguments for $meta_key, loop over the array and call update_user_meta for each key/value pair in the array.

EDIT:

WordPress doesn't give a built in way to update multiple metas at once. Part of the reason for using their built in function is because filters and hooks can be registered to operate on the meta information. These won't be called if you update them directly.

That said, you can try something like this (code untested):

$columns  = implode(" = '%s', ", array_keys($metas)) . " = '%s'";
$values   = array_values($metas);
$values[] = $user_id;
$table    = _get_meta_table('user');
$sql      = "UPDATE $table SET $columns WHERE user_id = %d";
$wpdb->query(
    $wpdb->prepare($sql, $values)
);
drew010
  • 68,777
  • 11
  • 134
  • 162
  • 2
    i'm trying to update all the meta data fields using one update – Fadi Jun 03 '15 at 04:41
  • There is no way to do that built-in for reasons mentioned in my edit, but there is some code you can try to modify to do what you want. – drew010 Jun 03 '15 at 05:18
  • 2
    Bear in mind that `update_user_meta()` will also insert the value if it doesn't exist. Running an `UPDATE` query on the DB directly will only update existing values. – Mark Parnell Jan 06 '16 at 03:06
  • `wp_update_post` does take `meta_input`. [It's just a loop internally](https://github.com/WordPress/WordPress/blob/631f08096bea41722a67e6b2e70d50ae0e2d3508/wp-includes/post.php#L4518-L4522) though, so there's no performance benefit. – Ian Dunn Mar 08 '22 at 22:34
5

just try to add the value with the same meta key,and remember to set the third value to false just like

add_user_meta( $user_id , $meta_key , $value1 , false );
add_user_meta( $user_id , $meta_key , $value2 , false );
add_user_meta( $user_id , $meta_key , $value3 , false );

then when you get user meta with the meta key ,it will return like:

['$value1','$value2','$value3']
yaime dc
  • 71
  • 1
  • 3
0

$userid = get_current_user_id();
$name = ;
$surname = ;

wp_update_user( array( 'ID' => $userid, 'first_name' => $name, 'last_name' => $surname ) );

JustMe
  • 1