How to update user meta for multiple meta_key in wordpress

不羁的心 提交于 2019-11-30 04:55:25

问题


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?


回答1:


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)
);



回答2:


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']


来源:https://stackoverflow.com/questions/30610780/how-to-update-user-meta-for-multiple-meta-key-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!