How to limit authors to their own posts in WordPress admin

If you have a multi-user blog you maybe have this problem that the authors can see all the posts when they only must see their own posts. So How to limit authors to their own posts in WordPress admin?

[lwptoc]

Here an image explains the problem of the post list on admin:

posts in WordPress admin

Although the author can only edit his posts, it is better than for default the other posts don’t appear.

 

How avoid the authors see all the posts in WordPress

We use the pre_get_posts hook for this purpose. But! you must be very careful with this hook because it affects the entire web (backend and frontend). If you use the correct conditions everything will be fine.

<?php
if( !function_exists('letsgodev_limit_posts') ) {
  function letsgodev_limit_posts($query) {
    global $pagenow;

    // If the user is on the post list
    if( 'edit.php' != $pagenow || ! $query->is_admin )
      return $query;

    // If the user can the capability to edit other posts
    if( current_user_can( 'edit_others_posts' ) )
      return $query;

    global $user_ID;
    $query->set( 'author', $user_ID );

    return $query;
  }

  add_filter( 'pre_get_posts', 'letsgodev_limit_posts');
}

 

Code explanation

The first conditional: will apply the script if the user is in the post list on admin. If he is not in this section so the script must no apply.

The second conditional: will apply the script if the user has no permission to edit another post because if the user can edit others is probable that this user is edit or administrator.

Finally, the script gets the ID of the current user (with active session) in the $user_ID variable and sets it to the query, so the list now has a new filter ( or where statement).

 

Result:

Now when the author goes to the post list on admin, he will see only his posts.

 limit authors to their own posts in WordPress

If you liked this article, please share it.

4 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x