Attila came up with this idea since we have a multi-contributor blog but no way to filter posts by a specific author. This simple snippet adds an author dropdown next to the dates and categories dropdowns. For instance, these appear on the All Posts screen of the WordPress admin dashboard, but they can be present for other post types as well. Natively, there is only a filter for posts that are “mine”. While it works well, why not have the ability to choose anyone else? It looks like this:
The author dropdown PHP snippet
Take this code and add it to your WordPress site:
add_action('admin_init', 'lwp_4694_admin_init');
function lwp_4694_admin_init() {
add_action('restrict_manage_posts', 'lwp_4694_author_dropdown');
}
function lwp_4694_author_dropdown(){
if ($GLOBALS['pagenow'] !== 'edit.php') {
return;
}
$screen = get_current_screen();
if (empty($screen)
|| ($screen->id !== 'edit-page' && $screen->id !== 'edit-post')
) {
return;
}
wp_dropdown_users(array(
'show_option_all' => 'All Authors',
'selected' => get_query_var('author', 0),
'name' => 'author'
));
}
That’s it. What do you want me to say about a snippet whose guard clauses are longer than the payload? 😀 Interestingly, the author dropdown integrates well with the already-present Filter button. Upon my test, I noticed that it works just fine with other filters and ordering choices. Moreover, I limited the scope to posts and pages, as many custom post types by 3rd party plugins don’t distinguish content by authors that much. The handy WordPress filters and functions used are (so you don’t have to Google in order to learn):
Without these, the code would have been much, much longer. The one that creates the actual dropdown is the hero of the day. With its selected argument, I pass the selected user’s ID back to it, so the select element remembers the chosen author.
Another approach?
By the way, if you don’t want a dropdown, click an author’s name in the appropriate column, and the All Posts screen filters to that name. What if the first page of this screen doesn’t have a post from the author I need? Not practical. Therefore, I found it more convenient to have an author dropdown, so all choices are at hand all the time. Hopefully, this snippet can help you and your team, let us know in the comments if it does!
Comments are closed.