0

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

  • What is the output you are getting? If you use print_r($authors_three_posts) what do you see? And 'posts_per_page' should be 5, not 3 – Ashok Kumar Nath Oct 23 '14 at 9:04
3

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' );
| improve this answer | |
  • echo '<h5>Latest Posts by Sam</h5>'; Will make this dynamic too. Apart from that +1 – Pieter Goosen Oct 23 '14 at 11:02
  • Very good catch @PieterGoosen, just edited! – Bordoni Oct 23 '14 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.