Get a user’s most recent post title

If I have a user’s ID, what’s the best way for me to get the title of that user’s most recent post?

Related posts

Leave a Reply

2 comments

  1. You just set the ‘author’ parameter in a WP_Query query or get_posts (which accepts the same parameters):

    $recent = get_posts(array(
        'author'=>1,
        'orderby'=>'date',
        'order'=>'desc',
        'numberposts'=>1
    ));
    if( $recent ){
      $title = get_the_title($recent[0]->ID);
    }else{
      //No published posts
    }
    

    (Note the ‘orderby’ and ‘order’ here are redundant because they are set to their default values, but you get the idea)

  2. The best way would be a custom SQL query, but you can simply use the native functions like get_posts() and that would be just fine as well;

    $args = array(
        'posts_per_page' => 1,
        'post_author'    => $user_id,
    );
    $posts = get_posts( $args );
    if ( $posts ) {
        echo $posts[0]->post_title;
    }