Sal B
Sal B

Reputation: 540

Display Author Name (outside of loop)

I have an area of my index.php file that I'm customizing in a theme whereby I would like to display the most recent post and some additional meta. I was able to pull the featured image, post title (and link), & the date; but not the author. I've tried various examples from the WP boards with no luck. The latest attempt below:

<?php
        $args = array( 'numberposts' => '1');
        $recent_posts = wp_get_recent_posts( $args );
        $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
        //$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));

        foreach( $recent_posts as $recent ){
            $post_author = get_user_by( 'id', $recent->post_author );
            echo '<div class="full-width" id="featured-post" style="background-image: url('. $feat_image .')">';

            echo '<div class="row featured-post-meta"><div class="small-8 columns">';
            echo '<h2><a href="' . get_permalink($recent["ID"]) . '" title="Read: '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a></h2>';
            echo '<p>'. $post_author->display_name .' | '. get_the_time('F jS, Y') .'</p>';
            echo '<a class="read-post" href="'. get_permalink($recent["ID"]) .'">Read the post</a>';
            echo '</div></div></div>';
        }
    ?>

Upvotes: 0

Views: 1760

Answers (1)

Nathan Dawson
Nathan Dawson

Reputation: 19308

Inside your foreach loop:

$post_author = get_user_by( 'id', $recent['post_author'] );

This gets you the user object which looks like what you were trying to do with $curauth.

You could then output $post_author->display_name in place of $curauth.

echo '<p>'. $post_author->display_name .' ...

Upvotes: 1

Related Questions