0

I am not very advanced in php. I have this function that prevents wp-login.php access with redirection

add_action('init','custom_login');

function custom_login(){
global $pagenow;
if( 'wp-login.php' == $pagenow && !is_user_logged_in()) {
wp_redirect('http://yoursite.com/');
exit();
 }
}

from here -> Disable Or Redirect WP-login.php

which is actually redirecting and not allowing access to wp-login.php, which is the first thing i want to have, but for logging out just redirects to 'http://yoursite.com/'

What i want to add is:

1.When the user logout from front-end redirect to current page -probably i could do this with

get_permalink() 

    or 

$location = $_SERVER['HTTP_REFERER'];
wp_safe_redirect($location);

2.When the user logout from back-end redirect to home url.

-I know that i can use is_admin() to determinate the front and back -end areas, but i need a little help to make the magic :)

1 Answer 1

1

you can do that with this code (paste it to your functions.php)

function auto_redirect_external_after_logout(){
    // check if user is leaving from admin
    // is_admin() check would not work here probably as we left the admin already
    if ( false !== strpos( $_SERVER['HTTP_REFERER'], 'wp-admin' ) ){
        wp_redirect( 'http://www.example-from-admin.com' );
    } else {
        wp_redirect( 'http://www.example-from-front.com' );
    }
    //make sure to call exit after redirect
    exit;
}

//execute the code above on logout
add_action( 'wp_logout', 'auto_redirect_external_after_logout');
3
  • Thank you for the reply Levi, code works fine , i did something like that: function auto_redirect_external_after_logout(){ if ( false !== strpos( $_SERVER['HTTP_REFERER'], 'wp-admin' ) ){ wp_redirect( home_url() ); } else { $location = $_SERVER['HTTP_REFERER']; wp_redirect( $location ); } exit; } add_action( 'wp_logout', 'auto_redirect_external_after_logout'); I guess first IF statement is to check if user is in the back-end yes? Is this going to work, if my website is over https? Also how can i disable wp-login.php, or redirect? Commented Nov 4, 2017 at 10:26
  • Yeah, in the first if statement we check what was the last page before the current script started to be executed, strpos() is used to check if wp-admin was part of this url. It will work with https as well. What do you mean by disabling wp-login? How would you log in as an administrator if you redirect that page? Commented Nov 4, 2017 at 20:46
  • Well, I already have front-end way to login with a widget, so i would also like to include disabling or not giving access to the wp-login page, as you see in my above code. Commented Nov 6, 2017 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.