How to Block Dashboard Access for Non-Admins WordPress

How to Block Dashboard Access for Non-Admins WordPress
745 Views
0
(0)

Removing the Admin Bar for Non-Admins

Removing the admin bar is a simple code snippet. I’ve shown before how you can hide the admin bar conditionally for users. In there I’ve not mentioned how you can hide it for everyone but admins, so thats where this code snippet comes in. You need to add the code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin.

<?php
/**
 * Hide admin bar for non-admins
 */
add_filter( 'show_admin_bar', 'cxc_hide_admin_bar_callback' );

function cxc_hide_admin_bar_callback( $show ) {
	if ( ! current_user_can( 'administrator' ) ) {
		return false;
	}

	return $show;
}
?>

Block Dashboard Access for Non-Admins

The best way to handle someone trying to access the dashboard is to redirect them to another page. You can consider redirecting them back to the primary landing page of your site, their front-end profile (if there’s any) or just redirect them back to the page they came from.

<?php
/**
 * Block wp-admin access for non-admins
 */
add_action( 'admin_init', 'cxc_block_wp_admin_access_callback' );

function cxc_block_wp_admin_access_callback() {
	if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
		wp_safe_redirect( home_url() );
		exit;
	}
}
?>

Disable Admin Bar for all users

Go to Appearance → Theme Editor → function.php. Scroll down to the end of the page and insert the following code snippet.

<?php
add_filter( 'show_admin_bar', '__return_false' );
?>

Disable the admin bar by using CSS

You can also disable the admin bar by using CSS. Just go to AppearanceCustomizeAdditional CSS and add the following CSS code:

#wpadminbar { display:none !important; }

Hiding the admin bar for a specific user

This is easy. You can hide the admin bar for specific users from the dashboard.

Go to Users → All Users. Select the user you want to hide the admin bar for. Uncheck the Show Toolbar when viewing site option and save changes.

FAQ

How can I prevent non-admins from accessing the dashboard?

Redirecting someone who attempts to access the dashboard to another page is the best method to manage the situation. Consider redirecting them back to your site’s main landing page.

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *