admin管理员组

文章数量:1327962

I have some posts that author is Administrator and some other posts that author is Editor

After logging in as Editor, I can edit Administrator posts. I would like to prevent this.

I find some information about filters like user_has_cap and map_meta_cap but i'm not sure it's right direction. Maybe I'm digging too deep and a simpler solution is nearby?

I have some posts that author is Administrator and some other posts that author is Editor

After logging in as Editor, I can edit Administrator posts. I would like to prevent this.

I find some information about filters like user_has_cap and map_meta_cap but i'm not sure it's right direction. Maybe I'm digging too deep and a simpler solution is nearby?

Share Improve this question asked Jul 30, 2020 at 11:15 kanlukaszkanlukasz 5448 silver badges24 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

map_meta_cap is the correct filter to use.

When WordPress checks whether you have permission to edit a post it checks edit_post. If you are the author of that post, that is mapped to the edit_posts capability, but if you're not it is mapped to edit_others_posts. You can use this filter to add the additional condition that Editors cannot edit posts by Administrators, even if they have edit_others_posts.

In this example, when WordPress checks edit_post, if the post author was an administrator, then the current user also needs to be an administrator to edit it:

add_filter(
    'map_meta_cap',
    function( $required_caps, $cap, $user_id, $args ) {
        if ( 'edit_post' === $cap) {
            $post = get_post( $args[0] );

            if ( $post && user_can( $post->post_author, 'administrator' ) ) {
                $required_caps[] = 'administrator';
            }
        }

        return $required_caps;
    },
    10,
    4
);

本文标签: capabilitiesHow to prevent users with quoteditotherspostsquot capability from editing admin posts