How to Block Dashboard Access for Non-Admins WordPress

How to Block Dashboard Access for Non-Admins WordPress

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
 */
function hide_admin_bar_callback( $show ) {
	if ( ! current_user_can( 'administrator' ) ) {
		return false;
	}

	return $show;
}
add_filter( 'show_admin_bar', 'hide_admin_bar_callback' );
?>

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
 */

function block_wp_admin_access_callback() {
	if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
		wp_safe_redirect( home_url() );
		exit;
	}
}
add_action( 'admin_init', 'block_wp_admin_access_callback' );
?>
Was this article helpful?
YesNo

Leave a comment

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