Function to display post by specific author

I am trying to create a function that will display the 5 post made by a specific author.

Lets say the specific name of the Author is ‘Nick’ I don’t know how to excute it.

I am using global variables for $post and $authordata.

Here’s my snippet:

function display_post_via_specific_author() {

global $authordata, $post;  //Declare Global Variables

$authors_three_posts = get_posts( 
          array(
            'author' => $authordata->ID, 
             'posts_per_page' => 3
            )
           );                          

echo '<h5>Latest Posts by Sam</h5>';

$output = '<ul>';
foreach ( $authors_three_posts as $authors_post ) {
    $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . get_the_title($authors_post->ID) . '</a></li>';

}
$output .= '</ul>';

return $output;

}

Any suggestions on how to solve this

Solutions Collecting From Web of "Function to display post by specific author"

Here is how I would solve your problem since $authordata is not a variable that I recognize as a WordPress global.

function display_post_via_specific_author( $nicename ) {
    // Grab the user by `user_nicename`
    $author = get_user_by( 'slug', $nicename );

    $posts = get_posts( 
        array(
            'author' => $author->ID, 
            'posts_per_page' => 5
        )
    );

    $output = '<h5>Latest Posts by Sam</h5>';
    $output .= '<ul>';
    foreach ( $posts as $post ) {
        $output .= '<li><a href="' . get_permalink( $post->ID ) . '">' . get_the_title( $post->ID ) . '</a></li>';
    }
    $output .= '</ul>';

    return $output;

}

So it should be easy to query by author login calling the function like this:

echo display_post_via_specific_author( 'nick' );