12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Oct 10, 2021

WordPress Login Redirection Code Snippets

Sridhar Katakam

This members-only tutorial provides the code snippets for

  1. redirecting non-admin users after they log in to the homepage while letting admins go where they would usually be taken to.
  2. redirecting non-logged-in visitors to a particular page when they try to visit any page on the front end. Logged-in users and admins will continue to see all the pages normally. This snippet can be used for setting up a Coming Soon or Maintenance mode w/o a plugin.
  3. preventing users from getting taken to the wp-login page when they enter wrong or empty credentials in the WordPress login form.
  4. redirecting all users of a specific role from / (homepage) to /events.

All the following snippets can be added using a plugin like Code Snippets or in the child theme's functions.php or using a custom functionality plugin.

Redirect users after they log in

The following snippet will redirect non admin users after successful login to the homepage whereas admins will be taken to their dashboard at /wp-admin.

<?php

add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
/**
 * Redirect user after successful login.
 *
 * @param string $redirect_to URL to redirect to.
 * @param string $request URL the user is coming from.
 * @param object $user Logged user's data.
 * @return string
 */
function my_login_redirect( $redirect_to, $request, $user ) {
	// is there a user to check?
	if ( isset( $user->roles ) && is_array( $user->roles ) ) {
		// check for admins
		if ( in_array( 'administrator', $user->roles ) ) {
			// redirect them to the default place
			return $redirect_to;
		} else {
			return home_url();
		}
	} else {
		return $redirect_to;
	}
}

If you would like the logged-in users (that are not admins) to be taken after a successful login to a specific page say "Welcome", replace

return home_url();

in the above with

return site_url( '/welcome/' );

where welcome is the slug of the Page and pretty permalinks are enabled.

Source: https://developer.wordpress.org/reference/hooks/login_redirect/#comment-2074

Redirect visitors that are not logged in

In a customization task I recently completed, the requirement was to redirect any user that is not logged-in to the /sign-in page (where the login form is present).

  • Users that are not logged-in should be taken to /sign-in page.
  • register page is an exception i.e., visitors should be able to visit it.
  • /wp-admin and /wp-login.php should not be affected.

Here's the snippet for the above:

This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $599 one-time).

Already a member? Log in below or here.

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-ocalendar-check-omagnifiercrossmenuchevron-downarrow-right