Add Snippet To Project
If you’re managing a WordPress site with multiple users or authors, you may find it necessary to restrict certain users from accessing certain parts of the site. Fortunately, WordPress has a built-in system of User Roles and Capabilities that allows you to define exactly what each user can and cannot do on your site. In this article, we’ll take a look at how you can use User Capabilities to restrict access to certain areas of the WordPress Admin Dashboard.
function wpturbo_restrict_by_capability() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.', 'wpturbo' ) );
}
}
add_action( 'admin_init', 'wpturbo_restrict_by_capability' );
The code snippet presented here shows us how to restrict access to the WordPress admin area by checking a user’s capability. This can be useful if you want to limit access to certain sections of the WordPress admin area to specific users or roles.
First, we define a new function called wpturbo_restrict_by_capability(). Inside this function, we use the current_user_can() function to check if the current user has the ‘manage_options’ capability. This function returns true if the user has the specified capability and false if they do not.
If the user does not have the required capability, we use the wp_die() function to display an error message and terminate the current script execution. The error message is passed to this function using the __() WordPress syntax, which enables the error message to be translated into different languages.
Next, we hook the wpturbo_restrict_by_capability() function into the admin_init action. This action is triggered when a user attempts to access the WordPress admin area, after WordPress has loaded all core files and created the user object.
With this in place, only users with the ‘manage_options’ capability will be able to access the WordPress admin area. Other users will be presented with the error message specified in the wp_die() function and will not be able to proceed further.
This approach is ideal for developers or administrators who want to restrict certain sections of the WordPress admin area to specific users with the appropriate capabilities.
