Get userdata object & user meta through single function call

Ever found the need for getting userdata and usermeta values through single function call? Userdata are the information stored in WP_User object where as usermeta are stored in metadata table as different entries.

While accessing user related information, it could sometime become confusion about which object to look for. Say for example, first_name, last_name, description are all actually accessible from user_meta whereas user_login, ID are available through userdata object.

This can become a little headache to effectively get information about a user. I found it really annoying while developing the user meta based prefill functionality of eForm.

So I came up with a nice function which would get me userdata or usermeta values which ever is available. If nothing is available, then it will return a mentioned default value.

The return is also strip_tag -ed for security.

PHP Snippet to get userdata & meta

<?php
/**
 * Gets the user metadata.
 *
 * Collectively gets userdata from both meta data and user object
 *
 * This is a single method to get data from user table like first_name,
 * last_name or through get_user_meta
 * 
 * Return value is also sanitized to prevent XSS
 *
 * @param      string  $key      The meta or object key
 * @param      string  $default  The default value to return if not found
 * @param      int     $user_id  The user identifier Can be null to get current
 *                               logged in user
 *
 * @uses       get_userdata
 * @uses       get_user_meta
 *
 * @author     Swashata Ghosh www.intechgrity.com
 *
 * @return     string  The user metadata.
 */
public static function get_user_metadata( $key, $default = '', $user_id = null ) {
	// Check if user id is provided
	if ( null == $user_id ) {
		if ( ! is_user_logged_in() ) {
			return $default;
		} else {
			$user_id = get_current_user_id();
		}
	}

	// Now get userdata
	$userdata = get_userdata( $user_id );

	if ( ! $userdata ) {
		return $default;
	}

	// If it has object property
	if ( property_exists( $userdata->data, $key ) ) {
		return strip_tags( $userdata->data->{$key} );
	}

	// Doesn't exist, so check for meta
	$metadata = get_user_meta( $user_id, $key, true );

	// If empty
	if ( empty( $metadata ) ) {
		return $default;
	}

	return strip_tags( $metadata );
}

I hope it helps you in some way.

Leave a Reply