Show Author name in single.php (WordPress)

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.

Read More

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>

Related posts

Leave a Reply

3 comments

  1. In your single.php, you most likely have a call to the_post(). You’ll find WordPress template tags will work just fine after this line. In other words, you can use the_author in single.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, use get_the_author instead. the_author actually echos it for you already.

  2. 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:

        <?php the_post(); ?>
        <div class="bar_info">
             By: <?php the_author(); ?>
             <?php
                    foreach((get_the_category()) as $category) { 
                        echo category->cat_name.', ';
                    }
             ?>
        </div>
    

    Alternatively this would also work:

         <?php the_post(); ?>      
         <div class="bar_info">
             echo "By: " . get_the_author();
                    foreach((get_the_category()) as $category) { 
                        echo category->cat_name.', ';
                    }
             ?>
        </div>
    
    • Use the_author in you single.php inside post loop.
    • you can use echo get_the_author instead of the_author.
    • You can use the_author_posts_link if you need author name with archive link.