Search code examples
wordpressupdatesuser-roles

How can I permanently modify Wordpress' wp-admin/post.php?


To resolve stupidity with a 3rd-party plugin, I had to give subscriber level users some edit capabilities that I don't want them to actually have. (This does not give them access to edit links, but they could access the edit URL directly if they were clever.) Since my site has only subscriber and administrative users, I can solve the problem by simply amending the capability check in wp-admin/post.php to require an additional capability that subscribers don't have, like so:

    if ( ! current_user_can( 'edit_post', $post_id ))
    wp_die( __( 'Sorry, you are not allowed to edit this item.' ) );

Becomes:

    if ( ! current_user_can( 'edit_post', $post_id ) OR ! current_user_can('edit_pages'))
    wp_die( __( 'Sorry, you are not allowed to edit this item.' ) );

This works perfectly, but I know that it will be overwritten and need to be re-done every time Wordpress updates. Is there a way to apply this fix in a more permanent manner via a filter or similar?


Solution

  • You don't need to modify post.php file. Use this code in your functions.php:

    add_filter('user_has_cap',function($allcaps,$need_caps, $args) {
        if ($_SERVER['SCRIPT_NAME']=='/wp-admin/post.php' && isset($_GET['action']) && $_GET['action']=='edit' && $args[0]=='edit_post' && ! current_user_can('edit_pages')) {
            foreach ($need_caps as $cap) {
                unset($allcaps[$cap]);
            }
        }
        return $allcaps;
    },10,3);