WordPress: Get user object for author of current post

Thoughts from the team
By    | August 21, 2012 | Code Snippets,

I just wanted to get the user object for the author of the current post inside the loop, to my surprise this doesn’t seem to be provided as a built in function.

  • the_author() and get_the_author() return (bizarrely) the public display name of the author
  • the_author_meta($field) requires you to specify a field key and returns a single value
  • get_currentuserinfo() returns the current logged in user

The we have the get user functions:

  • get_userdata($id) requires you to pass in the user ID
  • get_user_by($k, $v) lets you find a user by id, slug, email or login.

But we only have the display name for the author!?  Thankfully all is not lost.

  if (have_posts()) : while (have_posts()) : the_post();
    $author = get_userdata($post->post_author);
  endwhile; endif;

The magically global $post variable has an attribute post_author which returns the ID of the author.  We can then use get_userdata($id) to retrieve the author object.

Quite why this isn’t a core WordPress function I don’t know, we’ll be submitting it as a suggestion in the near future!

More like this