Hey guys, I have this points system on a project, everything works fine except that I can't add meta_values to multiple users.
I'm using <?php update_user_meta( $user_id, $meta_key, $meta_value, $prev_value ) ?>
but this seems to not work with multiple users.
Any idea?
Do you simply pass an array with user_ids to update_user_meta
? Then it won't work indeed.
Using a loop over all user_ids it should work:
foreach($user_ids as $user_id){
update_user_meta($user_id, $key, $value);
}
Think about the SQL being generated, while keeping in mind the database design of WordPress. It has the table wp_usermeta
, with columns user_id
, meta_key
and meta_value
. That means that every meta value has a row in this table, for every user. You could use some code as
global $wpdb;
$ids = implode("', '", $user_ids);
$wpdb->query($wpdb->prepare("UPDATE {$wpdb->usermeta} SET meta_value = %s WHERE user_id IN ('{$ids}') AND meta_key = %s"), $value, $key);
However this would not work if the meta_key
for a certain user does not exist yet. You would then need an INSERT
statement, which you can't do in a batch.
You can try something like;
$user_meta_fields = array ( 'first_name', 'last_name', 'account_type', 'vd_sub_name', 'description', 'vd_adress', 'vd_cp', 'vd_ville', 'vd_department', 'vd_region', 'vd_country', 'vd_tel', 'vd_gsm', 'vd_fax', 'url' );
foreach($user_meta_fields as $user_meta_field){
//echo "update_user_meta(".$user_id.", ".$user_meta_field.", ".$posted[$user_meta_field].");";
update_user_meta($user_id, $user_meta_field, $posted[$user_meta_field]);
}