WordPress login redirect

Sometimes we require users to log in to a WordPress site in order to access front-end functionality hidden from guests. In such instances, we can simply provide a standard login link:

<a href="<?php bloginfo('url'); ?>/wp-login.php">log in</a>

While this gets the job done, it takes users to the dashboard after they have logged in: they must then click on a link to return to the front-end, at which point an additional click may be required to get them back to the page they were viewing. Since WordPress 2.6.2 it has been possible to circumvent this round trip from origin to wp-login.php to wp-admin/ to / and finally back to origin by including a value for redirect_to in the href:

<a href="<?php bloginfo('url'); ?>/wp-login.php?redirect_to=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">log in</a>

The above returns users to their starting point after they've logged in.

Comments

Hi. Where does one put this juicy bit of code?

John Walker

@John If one visits /wp-login.php one is redirected to the dashboard after logging in. This may not be the way you wish a login link to operate. You may decide to hide the dashboard from your users entirely, in which case you will need to specify the page to which users are redirected by including a redirect_to value in the href of the login link.

awesome! I had been hoping to get this working - this made it possible. Thank you very much!

hi - great code, simple and works well.

one quick question - is it possible to do an exclude of the admin?

thanks!

paul

Good question, Paul. In most cases it is possible to cater a site's behaviour to a user's role. This explanation of how to check if a WordPress user is an "administrator" is worth a look.

In this case, however, the user's role is unknown at the time the page (and thus the redirect_to argument) is rendered. Changing the behaviour for admin users would require performing a check during the login process, which is beyond the scope of this post.

Remember, though, that simply visiting http://yoursite.com/wp-login.php will ensure that you are taken to the dashboard once logged in.

I swear you just saved my life with this little piece of code. Hehehe. Thanks!

Respond