Multiple update_user_meta in Wordpress

2019-09-17 07:51发布

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?

标签: php wordpress
2条回答
混吃等死
2楼-- · 2019-09-17 08:14

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]);
        }
查看更多
ら.Afraid
3楼-- · 2019-09-17 08:25

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.

查看更多
登录 后发表回答