How to get author’s name by author’s id

I want to show recent posts like this.

<ul id="recent-posts">
  <?php foreach( wp_get_recent_posts() as $recent ){ ?>
    <li>
      <a href="https://wordpress.stackexchange.com/questions/119829/<?php echo get_permalink($recent["ID']); ?>">
    <?php echo $recent["post_title"]; ?> by
    <?php echo $recent["post_author"]; ?>
      </a>
    </li>
  <?php } ?>
</ul>

But $recent["post_author"] returns only id of author. And this is outside The Loop, so I can’t use the_author() function.

How can I get author’s name from ID?
Or maybe there is a better way to do it?

4 s
4

Try get_user_by():

get_user_by( $field, $value );

In your case, you’d pass ID, and the user ID:

// Get user object
$recent_author = get_user_by( 'ID', $recent["post_author"] );
// Get user display name
$author_display_name = $recent_author->display_name;

Leave a Comment