admin管理员组

文章数量:1395198

I'd like to give contributors permission to edit only some of their own published pages.

I can use the following if I want to allow them to edit all of their published posts. How do I filter it allowing only certain pageids?

//to add capability to user
$user = new WP_User( $user_id );
$user->add_cap( 'edit_published_posts');

I'd like to give contributors permission to edit only some of their own published pages.

I can use the following if I want to allow them to edit all of their published posts. How do I filter it allowing only certain pageids?

//to add capability to user
$user = new WP_User( $user_id );
$user->add_cap( 'edit_published_posts');
Share Improve this question asked Feb 3, 2020 at 12:44 MohitMohit 1667 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can use user_has_cap filter to check and grant capabilities dynamically.

add_filter('user_has_cap', 'contributor_can_edit_published_posts', 10, 4);
function contributor_can_edit_published_posts($allcaps, $caps, $args, $user) {
  global $post;
  // Do we have a post?
  if ( ! $post ) {
    return $allcaps;
  }    
  // Is the user a contributor?
  if ( ! isset( $allcaps['contributor'] ) || true !== $allcaps['contributor'] ) {
    return $allcaps;
  }
  // Is the user the author of the post
  if ( $post->post_author != $user->ID ) {
    return $allcaps;
  }
  // Is the contributor allowed to edit this post?
  if ( ! in_array( $post->ID, array(1,2,3,4,5) ) ) {
    return $allcaps;
  }
  // Can the user edit published posts already? Allow, if not
  if ( ! isset( $allcaps['edit_published_posts'] ) && true !== $allcaps['edit_published_posts'] ) {
    $allcaps['edit_published_posts'] = true;
  }
  return $allcaps;
}

本文标签: capabilitiesAllow Contributor to edit published post and filter by page id