admin管理员组文章数量:1290316
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?
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?
Share Improve this question asked Oct 23, 2013 at 15:20 ironsandironsand 5693 gold badges8 silver badges15 bronze badges4 Answers
Reset to default 13Try 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;
echo get_the_author_meta('display_name', $recent["post_author"]);
// code from deprecated.php function @get_author_name
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 with wp_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):
<ul id="recent-posts">
<?php foreach( wp_get_recent_posts() as $recent ){
$user_id = get_user_by('id', $recent["post_author"]); // Get user name by user id
?>
<li>
<a href="<?php echo get_permalink($recent['ID']); ?>">
<?php echo $recent["post_title"]; ?> by
<?php echo $user_id->display_name; ?>
</a>
</li>
<?php
} ?>
</ul>
In your case this could work:
<?php $user_info = get_userdata($recent["post_author"]);
echo $user_info->user_login; ?>
本文标签: How to get author39s name by author39s id
版权声明:本文标题:How to get author's name by author's id 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741497925a2381918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论