1

I am trying to retrieve each user's first and last name, phone, email, and address from the usermeta table. I'm having trouble selecting multiple meta_values, each with its own meta_key, using a single sql query.

I would like the data returned as

First Name, Last Name, Phone, Address, Email First Name, Last Name, Phone, Address, Email First Name, Last Name, Phone, Address, Email First Name, Last Name, Phone, Address, Email

I have access to the actual DB via phpMyAdmin, so I would like help with the mySql query.

  • 2
    Is there a compelling reason to not use get_user_meta()? (Or, more abstractly, get_metadata()?) – Pat J Sep 9 '14 at 20:48
  • @PatJ As an answer please. – kaiser Sep 22 '14 at 19:27
  • 1
    Custom sql queries should be avoided if there is an already native function that will do the job. If a native function does not exist to do the job, and you need to use a custom sql query, you probably need to submit this as a request to include it in future releases of Wordpress – Pieter Goosen Sep 23 '14 at 4:39
  • under slightly different circumstances, get_user_meta() would be the best route to go. Although as stated in the OP, I am looking for the mysql query. I only have direct access to the database. – brandon-estrella-dev Sep 23 '14 at 20:14
3

You can just call get_user_meta without specifying a key, and it will return all MetaValues for the user.

$userdata = get_user_meta( $userID );

You may have to do a mapping for displaytitles of the Metavalue, as they are returned in an array, where the keys are the databasevalues of your metakeys.

For example, you may get

$userdata['f711_email_first_name']

If you want to display all these elements in a table, create an array like this:

$displaytitles = array(
    'f711_email_first_name' => 'Email first name',
    ...
);

When you loop through $userdata, you may output it like this:

foreach ( $userdata as $thisdata => $value ) {
    echo $displaytitles[$thisdata] . ': ' . $value[0];
}
1

If I was in your shoes, I'd use get_user_meta().

// get the users -- I'm ordering them by their username
$args = array( 
    'orderby' => 'login',
    'order' => 'ASC',
);
$users = get_users( $args );
foreach( $users as $user ) {
    $user_meta = get_user_meta( $user->ID );
    var_dump( $user_meta ); // to show you what you've got
}

This is a very simplistic example; in real life you'll probably want to loop through the array that get_user_meta() returns, and display things much more nicely than var_dump() does.

References

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.