I want to use $wpdb to get user's firstname. I know how to do it with php and mysql query, but I want to use $wpdb.

The problem is that I don't know how to use it. I tried to create simple query to display user fist_name by user_id and than echo it. This is what I ended up with:

$mywpdb1 = $wpdb->get_var( 
        "SELECT first_name 
        FROM $wpdb->usermeta 
        WHERE user_id = 2", 
echo $mywpdb1;
  • 1
    I see you are using $user->first_name. If you have a $user object, $user->first_name already contains the first name field. You don't need to do anything else. – cybmeta Oct 2 '15 at 8:44

You should'nt really be using wp query here, use get_user_meta();


$first_name = get_user_meta(2, 'first_name', true);

If you want to make a direct database query for first_name meta field the correct way is:

global $wpdb;

$user_id = 2;
$meta_key = "first_name";

$first_name = $wpdb->get_var( 
        "SELECT meta_value 
        FROM $wpdb->usermeta 
        WHERE user_id = %d 
        AND meta_key = %s",

echo $first_name;

But I think it is better to use the WP_User object, which contains the first_name meta field as a public property:

// Get the user with ID = 2
$user = new WP_User( 2 );

// Grab de the first_name
$first_name = $user->first_name;

You can use get_user_meta() function also, as suggested by @PaulH:

$first_name = get_user_meta(2, 'first_name', true);

But I thhink WP_User object is better than get_user_meta() for this specific case for these main reasons:

  1. Usually, when working with users you have to load the user object anyway. For example, in the description of question the user object is already loaded, so there is no need for anything else, just use $user->first_name.
  2. I don't think there is a huge perfomance difference between both methods but looking how get_user_meta() works (at the end it uses this function), it loads all user meta fields, even if you only want one field. That may have a worst perfomance than loading a WP_User object in some situations.
  • Why would you load the entire user object if you only need the first_name? Performance-wise using get_user_meta is superior. – Paul Oct 2 '15 at 12:06
  • I've updated the answer explaining why I think it is better to use user object in this specific case. Are you sure the performance is better using get_user_meta()? I don't think so for this case. – cybmeta Oct 2 '15 at 17:22

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.