11

I simply wonder why <?php var_dump(get_user_meta(4)); ?> doesn't contain an email address of the user. Instead I have to use

get_userdata(4)->user_email; to query the email of the user.

Why is that or did I miss something? get_user_meta() seems to provide all other aspects and informations of a user, however just not the email-address.

Matt

3 Answers 3

11

get_user_meta retrieves a single meta field or all fields of the user_meta data for the given user.

This means that all the values that are stored in user_meta table can be got using get_user_meta. Email is not stored as meta data so you cant get email using get_user_meta.

Email is stored with username and password in user table as user data.

2
14

Just wanted to let you know you have get_user_meta and get_userdata. The email address can be found using the get_userdata function.

For the current user this code can apply:

<?php

  $user_id = get_current_user_id(); 
  $user_info = get_userdata($user_id);
  $mailadresje = $user_info->user_email;
  echo $mailadresje;

?>

Please note this is applicable to the current user. If you need to get the user_id of let's say an order you need the following code (which I used to display the users mail on the invoice in WooCommerce) :

<?php

  $user_id = $wpo_wcpdf->export->order->user_id;
  $user_info = get_userdata($user_id);
  $mailadresje = $user_info->user_email;
  echo $mailadresje;

?>

Happy programming!

1
0

If you'd like to just return the user email from a user id and not load the entire user object, here is a quick function which utilizes the $wpdb global variable:

function get_user_email($user_id){
  global $wpdb;
  return $wpdb->get_var($wpdb->prepare("SELECT user_email FROM wp_users WHERE id=%d", $user_id));
}
3
  • Is that actually more efficient? I'd guess the other way is still only one database read, and might be in the request's in-memory cache too.
    – Rup
    Mar 14, 2023 at 16:06
  • Yes it's more efficient. get_userdata() will trigger update_meta_cache() which queries the user's meta data within the wp_usermeta table. Mar 15, 2023 at 17:28
  • OK, fair enough. WP_User::get_data_by( 'id', $user_id ) then, which does the cache but not the meta etc.
    – Rup
    Mar 15, 2023 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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