WordPress redirect automatically login page if user not logged-in

This code has to be inserted functions.php bottom, in this case if users are not login-in script has to redirect to login page.
After login if user has administrator privilegies it redirect to admin control panel if it isn’t and user has suscbriber privilegies it’s redirect to home-page URL.

function login_redirect() {

// Current Page
global $pagenow;

// Check to see if user in not logged in and not on the login page
if(!is_user_logged_in() && $pagenow != ‘wp-login.php’)
// If user is, Redirect to Login form.
auth_redirect();
}
// add the block of code above to the WordPress template
add_action( ‘wp’, ‘login_redirect’ );

////

function my_login_redirect( $redirect_to, $request, $user ) {
//is there a user to check?
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
//check for admins
if ( in_array( ‘administrator’, $user->roles ) ) {
// redirect them to the default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}

add_filter( ‘wp’, ‘my_login_redirect’, 10, 3 );

function my_login_logo() { ?>

add_action( ‘login_enqueue_scripts’, ‘my_login_logo’ );

References:
https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect

Deja una respuesta