Using WordPress ‘get_most_recent_post_of_user()’ PHP function

The get_most_recent_post_of_user() WordPress PHP function retrieves the most recent post of a user.

Usage

get_most_recent_post_of_user( $user_id );

Example:

// Retrieves the most recent post of user with ID 42
$latest_post = get_most_recent_post_of_user( 42 );

Parameters

  • $user_id (int) – Required. The ID of the user whose most recent post you want to retrieve.

More information

See WordPress Developer Resources: get_most_recent_post_of_user()

Examples

Display the title of the most recent post by a user

This example retrieves the most recent post by a user with the ID 42 and displays its title.

$user_id = 42;
$latest_post = get_most_recent_post_of_user( $user_id );
echo 'Latest post: ' . $latest_post['post_title'];

Show the date of the most recent post by a user

This example retrieves the most recent post by a user with the ID 42 and displays its date.

$user_id = 42;
$latest_post = get_most_recent_post_of_user( $user_id );
echo 'Latest post date: ' . $latest_post['post_date_gmt'];

Redirect to the most recent post by a user

This example retrieves the most recent post by a user with the ID 42 and redirects the visitor to the post’s URL.

$user_id = 42;
$latest_post = get_most_recent_post_of_user( $user_id );
wp_redirect( get_permalink( $latest_post['ID'] ) );
exit;

List the most recent post of all authors

This example retrieves the most recent post for each author on the website and lists their titles.

$authors = get_users( array( 'who' => 'authors' ) );

foreach ( $authors as $author ) {
    $latest_post = get_most_recent_post_of_user( $author->ID );
    echo 'Latest post from ' . $author->display_name . ': ' . $latest_post['post_title'] . '<br>';
}

Display an excerpt of the most recent post by a user

This example retrieves the most recent post by a user with the ID 42 and displays an excerpt of its content.

$user_id = 42;
$latest_post = get_most_recent_post_of_user( $user_id );
echo wp_trim_words( $latest_post['post_content'], 30, '...' );