stop redirection on /wp-admin call to /wp-login

thanks to Tomasz Struczynski
who has explained and answered my question completely

You Can See The Answer At This Link


First – explanation.

WordPress is kind of tricky, when it comes to admin pages. Essentially, when admin page is being loaded, wp-admin/admin.php is being included. Inside this file there is a call to a function called auth_redirect() It checks, if user is logged in, and if not – redirects him to a login page.

As this function is not a typical action/filter, it is kind of hard to disable it. Fortunately, it calls several hooks on its own. One of them, auth_redirect_scheme, is called just before real redirection happens. It is meant to prepare a ‘scheme’ (http/https) for redirection, but we can exploit it to suit your goals.

I added a filter hook for auth_redirect_scheme, with priority 9999 (it does not really matter, but I wanted it to run late, just in case). I then took a piece of code from original auth_redirect() used to check, if user is logged in (wp_validate_auth_cookie). If he is, we just return value, as nothing has to be done. If the user is not logged in, though, we show an error page and exit the script (to prevent redirect of happening).

Also, just in case I disabled wp_redirect_admin_locations filter. I’m not really sure, if this is needed, but…

And now – the code. Mind, this might not be the perfect solution and will require some improvements from your part.

<?php
/**
 * @packageStop_Redirect
 */
/*
Plugin Name: Stop redirect
Plugin URI: 
Description: Stop redirecting anything to wp-login
Author: Tomasz StruczyƄski
Version: 0.1
Author URI: 
*/

add_action('init', 'remove_default_redirect');
add_filter('auth_redirect_scheme', 'stop_redirect', 9999);

function stop_redirect($scheme)
{
    if ( $user_id = wp_validate_auth_cookie( '',  $scheme) ) {
        return $scheme;
    }

    global $wp_query;
    $wp_query->set_404();
    get_template_part( 404 );
    exit();
}

function remove_default_redirect()
{
    remove_action('template_redirect', 'wp_redirect_admin_locations', 1000);
}

Leave a Comment