How to let a user level edit custom post type made by anybody?

I am not an expert in PHP/WordPress and I am running a WP site with multiple user levels. I have already created a custom post type called “race”. I would like to allow the Contributor level able to edit “races” that have been published from any other user, not only by themselves.

Currently, only the Author can do this, while Contributor can only edit the “races” himself has published.

Read More

The custom post type was made by CPT UI plugin and I did not code it myself.

I have a user role / capabilities plugin (“User Role Editor” and “Members”) and I know how to use them once the capabilities are registered, but I do not know how to set up the capabilities for a custom type post.

I think this entry is related to my problem (the last bit of code) but I do not know how to adapt it in the case that the post type already exists, and in which files the code should be inserted to.

PS. As a second step, I would like for edits to have to be approved by an Author anytime they are made by a contributor. Currently, if a contributor edits his own “race”, the changes are published immediately. Approval is only needed for initial publication right now.

Related posts

Leave a Reply

2 comments

  1. WordPress has a filter, it is used to check your capability called “user_has_cap”. We can add “edit_other_posts” and “edit_published_posts” for Contributor through this. I have a code here for you, you can put it on your theme functions.php file or any php file in your plugin, try it:

    function allow_user_edit_race_post( $all_caps, $caps, $name, $user ) {
        if( is_user_logged_in() && $name[0] == 'edit_post' ) {
            global $current_user;
            $post = get_post( $name[2] );
            if( in_array('contributor', $current_user->roles ) && ! is_wp_error($post) && $post->post_type == 'race' ) {
                $all_caps['edit_others_posts'] = true;
                $all_caps['edit_published_posts'] = true;
            }
        }
        return $all_caps;
    }
    add_filter( 'user_has_cap', 'allow_user_edit_race_post', 10, 4 );
    

    Hope this help!

  2. Add this bit of code to your functions file:

    function wp_change_cap_type() {
       global $wp_post_types;
       $wp_post_types['race']->capability_type = 'race';
    }
    add_action('init', 'wp_change_cap_type');
    

    Then assign the capability ‘edit_others_races’ and ‘edit_races’ to the Contributor role and any others that you want to have the capability (Editor, Administrator, etc). Do not assign ‘publish_races’ to the Contributor role, as only the Author is supposed to do that.