How to Only Show the Author’s Posts in the WordPress Edit List

Home » Snippets » How to Only Show the Author’s Posts in the WordPress Edit List
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you running a multi-author website? Do you want each author on your WordPress site to view and manage only their own posts in the edit list? If so, this is just the guide for you. In this article, we will show you how to restrict WordPress post edit list to display only the posts created by the logged-in author, improving organization and privacy on your multi-author site.

					function wpturbo_show_only_author_posts($query) {
    global $current_user;
    if($query->is_admin && !current_user_can('edit_others_posts')) {
        $query->set('author', $current_user->ID);
    }
    return $query;
}
add_filter('pre_get_posts', 'wpturbo_show_only_author_posts');
				

The wpturbo_show_only_author_posts function is designed to modify the default query used by WordPress when displaying posts in the dashboard, in a way that it only returns posts written by the currently logged-in user.

The $query parameter that’s passed into the function represents the specific WordPress query that’s about to be executed. Before the query is run, the function checks if the user is in admin mode and if they don’t have the edit_others_posts capability. This capability typically belongs to administrators and editors, but not to authors and contributors.

if($query->is_admin && !current_user_can('edit_others_posts')) {

This check ensures that admins and editors, i.e., users that can edit other people’s posts, still see all posts in the dashboard (not just their own).

Next, the $query->set('author', $current_user->ID); call modifies the argument of the $query object to filter posts by the author. By setting the author parameter to $current_user->ID, we ensure that the query will only return posts that are associated with the currently logged in user:

$query->set('author', $current_user->ID);

As soon as this modification is done, the function returns the modified query:

return $query;

Lastly the function wpturbo_show_only_author_posts is added to the ‘pre_get_posts’ filter. With this, WordPress will run wpturbo_show_only_author_posts before each query, ensuring that authors only see their own posts in the dashboard:

add_filter('pre_get_posts', 'wpturbo_show_only_author_posts');

Note that this applies to all post types. If you want to limit this behaviour to a specific post type, you could add an additional check in the if statement, like $query->query_vars['post_type'] == 'your_post_type'.

Register an account to save your snippets or go Pro to get more features.