4

I have a custom post type named project which has

'capability_type' => 'post'

while registering using register_post_type.

In my theme files and also functions.php file, I have situations where I should check if the project to be edited is authored by the user or not.

So I use this:

if ( !current_user_can( 'edit_post', $porject_id ) ) return;

where $project_id is post id of the project to be edited.

For example I have a page template named single_project.php where I can show single posts in project post type to users and I want these people can see each project single page:

  1. administrators
  2. editors
  3. the contributor (post author)

but using the above code, It is ok with administrators and editors, while not for the contributor himself!

When I use:

var_dump( current_user_can( 'edit_post', $project_id ) );

with the contributor logged-in account, it returns false, while this:

var_dump( current_user_can( 'edit_posts' ) ); // (with trailing 's')

returns true (but for every post, not just does for him).

Any help with this?

2 Answers 2

4

using map_meta_cap I added edit_post per post cap to user

function my_map_meta_cap( $caps, $cap, $user_id, $args ){
    if ( 'edit_post' == $cap ) {
        $post = get_post( $args[0] );
        $post_type = get_post_type_object( $post->post_type );
        $caps = array();
        if ( $user_id == $post->post_author )
            $caps[] = $post_type->cap->edit_posts;
        else
            $caps[] = $post_type->cap->edit_others_posts;
    }
    return $caps;
}
add_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 );
1

This is a very late answer, but the accepted answer is incorrect, and I've seen other users referring to it, so I'm submitting the correct answer.

The reason the Contributor user was seeing false for edit_post is that Contributors cannot edit posts that have already been published. Only roles with edit_published_posts can do that.

In the original question, the author says:

I have situations where I should check if the project to be edited is authored by the user or not.

That is not the same as whether or not a user can edit a post, which is what their code is actually checking. If you want to check whether the author of a post is a particular user, then that's what should be compared:

if ( get_current_user_id() === get_post_field( 'post_author', $project_id ) ) {
    // etc.
}
2
  • probably change === to ==, first one returns an integer while second one a string Commented Oct 18, 2021 at 17:51
  • 1
    @NabeelKhan, if that's the case, it probably would be better to typecast the second operand to an integer by prepending it with (int) Commented Jun 16, 2022 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.