Get userdata inside custom build plugin

There are 2 reasons why get_userdata fails and both are related to the fact that it is a pluggable function.

Pluggable functions can be overriden by plugins, so if a plugin override that function, and the plugin is poorly coded, that function can fail. However this is not the most common reason why using that function cause an error.

The reason why it happen, often is that is used in a wrong way.

Pluggable function are defined in the pluggable.php that is loaded after all the plugins are loaded, otherwise is impossible for plugins override functions in it.

So, if in a plugin you use that function without wrapping it in a proper hook, the function is not defined, and so the error.

You can solve the problem in 2 ways:

1. Wrap the function in a proper hook

add_action('plugins_loaded', function() {

  // stuff here where you get user id

  $user_data = get_userdata( $userid );

  // stuff here

});

The first hook you can use is 'plugins_loaded' but if you want to get info of current logged in user you should use 'wp_loaded' hook.

2. Don’t use pluggable functions

What get_userdata do, is just return an instance of WP_User that has the id you pass as argument. So, if you can use:

// stuff here where you get user id

$user_data = FALSE;
$data = WP_User::get_data_by( 'id', $userid );
if ( ! empty($data) ) {
  $user = new WP_User;
  $user_data = $user->init( $data );
}

and that is exactly the same of $user_data = get_userdata( $userid );.
This code work without wrapping it in hook, because WP_User class is defined in 'wp-includes/capabilites.php' file that is loaded very early.

However, is considered a good practice write code in plugin wrapping it in predictable hooks, so first solution is better.

If you want, you can use the best of both solutions, using a proper hook and avoid using a pluggable function that can be overridden by others plugins:

add_action('wp_loaded', function() {

  // stuff here where you get user id

  $user_data = FALSE;
  $data = WP_User::get_data_by( 'id', $userid );
  if ( ! empty($data) ) {
    $user = new WP_User;
    $user_data = $user->init( $data );
  }

  // stuff here

});

Probably this is the best solution.

Leave a Comment