I need to display the Author of the post in the single.php file in WordPress. The reference indicates that the_author(); only works within the loop.
I’ve been looking for others forums and nothing found.
Any idea?
Thanks.
EDIT:
<div class="bar_info">
<?php echo "By: ".the_author(); ?>
<?php
foreach((get_the_category()) as $category) {
echo category->cat_name.', ';
}
?>
</div>
In your
single.php
, you most likely have a call tothe_post()
. You’ll find WordPress template tags will work just fine after this line. In other words, you can usethe_author
insingle.php
.Edit: Based on the code you’ve updated in your question, you’ll need to put something like the following at the top of
single.php
:<?php if( have_posts() ) the_post(); ?>
Also, if you want to use the author name in an
echo
statement, useget_the_author
instead.the_author
actually echos it for you already.As long as there is a $post object, you are technically “in the loop” â even if only one post exists in the query object, which is the case in single.php. As long as you’ve executed the_post(); template tags are accessible, so the_author(); will work just fine. If you want to point to author archives the_author_posts_link(); will output a link to the appropriate archive as well as the author name in the anchor text.
UPDATE:
Also your code is wrong. the_author echos the author name, get_the_author() would treat it as a variable. This would work:
Alternatively this would also work: