Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

What measures I can take to solve this?

share|improve this question
add comment

1 Answer

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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