Snippets

cutiko Functions for non admins user avoid dashboard

Created by cutiko last modified
<?php

//The 3 following functions are ment for non admins to stay only in the website and never go to the dashboard
//This remove the admin bar for non admins
add_action('after_setup_theme', 'remove_admin_bar');

function remove_admin_bar() {
  if (!current_user_can('administrator') && !is_admin()) {
    show_admin_bar(false);
  }
}

//This array gets the user tole to be use in the next function for redirecting non admins
if( is_array( $user->roles ) ) {
	if( in_array( 'administrator', $user->roles ) ) {
		admin_url();
	} else {
		site_url();
	}
}

//This functions redirects non admins to the website instead of the dashboard since they dont have admin bar they cant go into the dashabord
function redirect_non_admins( $redirect_to, $request, $user  ) {
    return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
  }
add_filter( 'login_redirect', 'redirect_non_admins', 10, 3 );

?>


<?php 


/*I recently found this other snippet, wich way more easy to customize and can be combine with the admin bar remove from above*/

/**
 * WordPress function for redirecting users on login based on user role
 */
function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
        if( $user->has_cap( 'administrator' ) ) {
            $url = admin_url();
        } else {
            $url = home_url('/members-only/');
        }
    }
    return $url;
}
add_filter('login_redirect', 'my_login_redirect', 10, 3 );

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.