Accessibility – How to restrict access to all wp-admin pages for client users

So, I want to block customers’ access to all wp-admin menu/plugin pages including this link
https://mywebsite.com/wp-admin/user-edit.php?user_id=113

This is not a bulletproof solution, but it should work in the event that non-admin users will no longer be able to access any admin pages when they logged in,

add_action( 'admin_init', function () {
    if ( wp_doing_ajax() || ! is_user_logged_in() ) {
        return;
    }

    $roles = (array) wp_get_current_user()->roles;
    if ( ! in_array( 'administrator', $roles ) ) { // allows only the Administrator role
        wp_die( 'Sorry, you are not allowed to access this page.' );
        // or you can redirect the user to somewhere, if you want to
    }
} );

But then, you may want to change the login and registration redirect url so that it doesn’t send the user to an admin page on successful login/registration – see the docs for this login_redirect And registration_redirect,

The problem with this is that they can then create an API key (via the Application Password plugin which is accessible from that page).

i can’t help you with this Put, but unless you’re using WordPress prior to v5.6.0, you don’t need to use the plugin because application passwords have been a core feature in WordPress since v5.6. and there’s actually a hook called wp_is_application_passwords_available_for_user Which you can use to disable the feature for some users.

This is undesirable as I don’t want users to have API keys where they can fetch/post data to the server.

If so, and since you said in your comment, “Rest API restricted to authenticated users“, so how about using rest_authentication_errors How to ensure hooks only allow administrators to access the REST API?

Working example:

add_filter( 'rest_authentication_errors', function ( $errors ) {
    if ( ! is_wp_error( $errors ) ) { // do nothing if there's already an error
        if ( $can_access = is_user_logged_in() ) {
            $roles      = (array) wp_get_current_user()->roles;
            $can_access = in_array( 'administrator', $roles ); // allows only the Administrator role
        }

        if ( ! $can_access ) {
            return new WP_Error( 'user_not_allowed',
                'Sorry, you are not allowed to access the REST API.',
                array( 'status' => rest_authorization_required_code() )
            );
        }
    }

    return $errors;
} );

Leave a Comment