Add Snippet To Project
Have you ever needed to limit what certain users can see or do on your site? Whether you’re running a membership site, a forum, or a blog, there may come a time when you need to restrict user access to specific content or features. This can be complex and challenging especially for non-developers. However, with this guide, we aim to break down the process into clear, easy-to-follow steps. This article will help you understand how to effectively restrict user access in WordPress.
function wpturbo_restrict_access_to_admin() {
if (!current_user_can('administrator')) {
wp_redirect(home_url());
exit;
}
}
add_action( 'admin_init', 'wpturbo_restrict_access_to_admin' );
The code snippet provided enables you to restrict non-admin users from accessing the dashboard in WordPress.
The code begins by defining a new function called wpturbo_restrict_access_to_admin(). This is the function that carries out the operation of checking the user’s role and redirecting non-admin users.
Within wpturbo_restrict_access_to_admin(), an if-statement is executed. This statement calls WordPress’s built-in function current_user_can() in order to check if the current user has administrative privileges.
if (!current_user_can('administrator')) {
current_user_can('administrator') checks whether the user handling the current request is an admin or not. If the user is not an administrator, this will return false.
When it returns false, meaning a user without administrative permission, the code proceeds further and executes the wp_redirect(home_url()) function. This function redirects the non-admin user back to the home page of your WordPress site.
wp_redirect(home_url());
home_url() is a WordPress function which returns the homepage URL of your site, decided in your WordPress settings.
Also, exit; statement is important; it ensures our redirection takes effect immediately by terminating the current script.
Lastly, this wpturbo_restrict_access_to_admin function needs to be triggered when someone tries to access your admin dashboard. To do this, take advantage of WordPress action hook admin_init using add_action() function:
add_action( 'admin_init', 'wpturbo_restrict_access_to_admin' );
admin_init is triggered just before any other hook when a user tries to access the admin area of your WordPress website which makes it the perfect place to add our function. Thus, anytime a non-admin tries to access your WordPress dashboard, they are instantly redirected to the home page of your site, ensuring exclusive access to the admin area for admin user role only.
