Logging in to the frontend works correctly but not for WP-Admin

On my private page, I want the website to be shown only to logedin people. So if a person comes to the site, the first is displayed custom template login form. When the person log-in, the home page is displayed.

I have this redirect done with the following code:

add_action( 'template_redirect', function() {
  if ( ! is_user_logged_in()  ! is_page( array( 'prijava', 'pozabljeno-geslo' ) ) ) {
    wp_redirect( esc_url( home_url( '/prijava/' ) ) );
    exit;
  }
});

And the log in form using Ajax and the following code:

//add this within functions.php
function ajax_login_init(){

    wp_register_script('ajax-login-script', get_stylesheet_directory_uri() . '/assets/js/ajax-login.js', array('jquery') ); 
    wp_enqueue_script('ajax-login-script');

    wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 
        'ajaxurl' = admin_url( 'admin-ajax.php' ),
        'redirecturl' = home_url(),
        'loadingmessage' = __('Pošiljanje podatkov o uporabniku, počakajte ...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_login_init');
}


function ajax_login(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Nonce is checked, get the POST data and sign user on
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = $_POST['rememberme'];

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=false, 'message'=__('Napačno uporabniško ime ali geslo.')));
    } else {
        echo json_encode(array('loggedin'=true, 'message'=__('Prijava uspešna, preusmerjanje...')));
    }

    die();
}

Everything works normally for normal users. For administrators who need to access the WP-ADMIN page, it redirect them to the wp-login.php page, but why if they are already logged in, because otherwise the first home page would not show them?

Topic login Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.