Restrict acceess of a page in backend

How can I restrict editing of a page from backend only to a specific user?

I tried a few plugins but I thought doing it without plugins would be the way to go for me.

Read More

What measures I can take to solve this?

Related posts

Leave a Reply

1 comment

  1. This can be done in two steps. First, add a hook to the page /wp-admin/edit.php?post_type=page to remove the desired page from appearing to other users. And another hook to redirect non-authorized users from trying to access the page directly /wp-admin/post.php?post=ID&action=edit.

    Here, the post type is page, but it can be changed to any other. Make the adjustments indicated in the comments:

    /**
     * Adjust the following:
     * post_type
     * User ID
     * Post ID
     */
    
    add_action( 'load-edit.php', 'load_custom_filter_wpse_94387' );
    add_action( 'load-post.php', 'block_page_access_wpse_94387' );
    
    /**
     * Executed only in /wp-admin/edit.php
     *
     * Checks current post type and bail if not correct
     */
    function load_custom_filter_wpse_94387()
    {
        global $typenow;
    
        // Not the correct post type, do nothing
        if( 'page' != $typenow ) // <--- adjust
            return;
    
        add_filter( 'posts_where' , 'posts_where_wpse_94387' );
    }
    
    /**
     * If not authorized user, remove page from listing
     */
    function posts_where_wpse_94387( $where ) 
    {
        $current_user = wp_get_current_user();
    
        if ( 2 == $current_user->ID ) // <--- adjust
            return $where;
    
        $where .= ' AND ID != 119'; // <--- adjust
        return $where;
    }
    
    /**
     * Check if unauthorized user is trying to access restricted page
     */
    function block_page_access_wpse_94387()
    {
        // Check for post=119, if it is not this one, do nothing
        if( !isset( $_GET['post'] ) || '119' != $_GET['post'] ) // <--- adjust
            return;
    
        // Check for user, if allowed user, do nothing
        $current_user = wp_get_current_user();  
        if ( 2 == $current_user->ID ) // <--- adjust
            return;
    
        // Invalid attempt to edit the page, redirect
        wp_redirect( admin_url( 'edit.php?post_type=page' ) );
        exit();
    }
    

    Relevant Q&A’s:
    Where to put my code: plugin or functions.php?
    Update post counts (published, draft, unattached) in admin interface