PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to update user meta for multiple meta_key in wordpress

 October 24, 2022     meta-key, php, wordpress, wordpress-theming     No comments   

Issue

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?


Solution

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


Answered By - drew010
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing