The get_users_drafts() WordPress PHP function retrieves a user’s drafts.
Usage
$drafts = get_users_drafts($user_id);
Input:
$user_id
: The user ID for which you want to retrieve drafts.
Output:
- An array of drafts created by the specified user.
Parameters
$user_id (int)
: Required. The user ID for which you want to retrieve drafts.
More information
See WordPress Developer Resources: get_users_drafts()
Examples
Display a list of a user’s drafts
This example retrieves the drafts of user with ID 5
and displays them in an unordered list.
$user_id = 5; $drafts = get_users_drafts($user_id); echo '<ul>'; foreach ($drafts as $draft) { echo '<li>' . $draft->post_title . '</li>'; } echo '</ul>';
Count a user’s drafts
This example retrieves the drafts of user with ID 3
and displays the total number of drafts.
$user_id = 3; $drafts = get_users_drafts($user_id); $draft_count = count($drafts); echo "Total drafts: " . $draft_count;
Display drafts with creation date
This example retrieves the drafts of user with ID 7
and displays the title and creation date for each draft.
$user_id = 7; $drafts = get_users_drafts($user_id); foreach ($drafts as $draft) { echo "Title: " . $draft->post_title . "<br>"; echo "Creation Date: " . $draft->post_date . "<br><br>"; }
Get drafts within a specific date range
This example retrieves the drafts of user with ID 10
that were created between January 1, 2023 and May 1, 2023.
$user_id = 10; $start_date = '2023-01-01'; $end_date = '2023-05-01'; $drafts = get_users_drafts($user_id); $filtered_drafts = array_filter($drafts, function($draft) use ($start_date, $end_date) { return $draft->post_date >= $start_date && $draft->post_date <= $end_date; }); foreach ($filtered_drafts as $draft) { echo $draft->post_title . "<br>"; }
Sort drafts by last modified date
This example retrieves the drafts of user with ID 8
and sorts them by the last modified date in descending order.
$user_id = 8; $drafts = get_users_drafts($user_id); usort($drafts, function($a, $b) { return strtotime($b->post_modified) - strtotime($a->post_modified); }); foreach ($drafts as $draft) { echo $draft->post_title . " - " . $draft->post_modified . "<br>"; }