Programatically add metadata to user accounts in WordPress

Besides my full time regular job, these days I’m working on a community site for a friend of mine. Good knows if it will ever come to life 🙂 However, here’s a little something some of you might find useful. I needed to develop and export quite a large amount of users from a database of some other system into WordPress system. Among other things I needed to attach quite a few custom metadata fields to each and every user. WordPress already comes with function for creating/updating user metadata.
What I needed is a bit modified version, the one that receives an array of key values as metadata fields. Here is my tweak on how to do it.
/**
*
* @param int $userId
* @param array $data array of key values
*/
public function addMetaData2User($userId = 0, $data = array())
{
if(($userId > 0) && (!empty ($data)))
{
echo '<ul>';
foreach ($data as $key => $val)
{
if(update_usermeta($userId, $key, $val))
{
echo '<li>Added key <strong>'.$key.'</strong> with value <strong>'. $val .'</strong>';
}
}
echo '</ul>';
}
}
Just place this inside one of your custom classes or anywhere you prefer.
So if you would like to add the fields like “am_i_cool”, “total_points” and so on, then all you need to do is something like
$data = array( "am_i_cool" => "yes", "total_points" => "8");
addMetaData2User( $someUserIdNumberHere, $data);
Hope some of you find this useful.
4 comments
This is great, I figure there is a way todo this in mySQL but I found this, looks great.
I have imported a bunch of users, and need to marker them as imported so that I can tell the different between imported users and new users.
This is perfect! thanks
Thanks !
What if you want to update user metadata just once?
I mean, I need to execute this action one time only.
Where do I have to call this function ?
Thanks !
Hi Branko:
Thanks for the post. I’m also migrating users from a custom built system to BuddyPress, so this will come in handy. A couple of things you might have added to make the post more useful:
– how to allow users to update their metadata.
– how to retrieve and display the metadata.
Thanks again,
– AAA
Oi Branko,
I have a similar social network side project going. I initially was going to use ning but since they’re shutting down most of the developer access I started looking into alternatives, including modifying wordpress.
I’m going with the combo wordpress mu+buddypress+bbpress. It’s amazing how those have evolved in the last six months and how powerful combining these 3 is. It really is wordpress on steroids.
Might want to check them out.