I want to show recent posts like this.
<ul id="recent-posts">
<?php foreach( wp_get_recent_posts() as $recent ){ ?>
<li>
<a href="<?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?
Try
get_user_by()
:In your case, you’d pass ID, and the user ID:
More examples of get_the_author_meta($meta_key, $author_id) you can find at Codex.
The
wp_posts
table, which is the one you are querying withwp_get_recent_posts()
does not include an author name column. It only carries the author ID (as you have already found out).So, what you have to do is use another WordPress function called
get_user_by()
. This will allow you to take the author ID and find the corresponding author name.Something like this should work (untested):
In your case this could work: