Nick
Nick

Reputation: 4462

Function to redirect to subdomain when user logs into Wordpress site

I'm using the function below to redirect non-admin users to the home page of my site rather than the admin page on login, and I'm wondering if there is any way of adapting the function to point to a subdomain of my site?

I have tried entering the full URL of the subdomain in place site_url(), but this doesn't work. Is there another way of achieving this? Essentially I want the user to be redirected to our discourse forum on login.

function acme_login_redirect( $redirect_to, $request, $user  ) {
    return ( is_array( $user->roles ) && in_array( 'administrator', $user->roles ) ) ? admin_url() : site_url();
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );

Upvotes: 1

Views: 449

Answers (1)

danish
danish

Reputation: 383

The login_redirect filter calls wp_safe_redirect() if a string (url) is returned in the login_redirect filter function.

Then wp_safe_redirect() checks if the returned string (url) is in the list of allowed hosts or not, if the returned string exists in the allowed hosts then wp_safe_redirect() will redirect a user to that returned string (url) otherwise a user will be redirected to to wp-admin on the siteurl instead.

So before adding the login_redirect filter you should add host in the whitelist using allowed_redirect_hosts filter.

function my_allowed_redirect_hosts($content){
    $content[] = 'google.com'; // Do not add http://

    return $content;
}
add_filter( 'allowed_redirect_hosts' , 'my_allowed_redirect_hosts' , 10 );

function acme_login_redirect($redirect_to, $requested_redirect_to, $user) {
    if (is_array($user->roles) && in_array('administrator', $user->roles)) {
        return admin_url();
    }
    else
    {
        return 'http://google.com';
    }
}
add_filter( 'login_redirect', 'acme_login_redirect', 10, 3 );

For more info check allowed_redirect_hosts

To know more about how login_redirect works, go to login_redirect and scroll to line 807

Upvotes: 1

Related Questions