Using WordPress ‘auth_redirect()’ PHP function

The auth_redirect() WordPress PHP function is used to verify whether a user is logged in or not. If a user is not logged in, they will be redirected to the login page. The redirection is designed so that after successful login, users are taken back to the page they initially attempted to access.

Usage

To require a user to be logged in to view a page, use the following code:

if ( !is_user_logged_in() ) { 
    auth_redirect(); 
}

Parameters

  • This function does not have any parameters.

More Information

See WordPress Developer Resources: auth_redirect()

Please note that there is a known bug with this function. If the original page the user was trying to access required parameters, those parameters are not preserved after the redirect. Upon successful login, the page will load without the required parameters.

Examples

Redirect to Login from a Specific Page

If you want to require login for a specific page, like ‘my-page’, you can use the following code:

if ( is_page( 'my-page' ) && !is_user_logged_in() ) { 
    auth_redirect(); 
}

In this example, is_page( ‘my-page’ ) checks if the current page is ‘my-page’. If it is and the user is not logged in, they are redirected to the login page.

Redirect to Login from a Custom Post Type

If you have a custom post type and want to require login to access it, use the code below:

if ( is_singular( 'my-custom-post' ) && !is_user_logged_in() ) { 
    auth_redirect(); 
}

is_singular( ‘my-custom-post’ ) checks if the current page is a singular view of ‘my-custom-post’. If it is and the user is not logged in, they are redirected to the login page.

Redirect to Login from all Pages except Home

To require login for all pages except the home page, use this code:

if ( !is_home() && !is_user_logged_in() ) { 
    auth_redirect(); 
}

Here, is_home() checks if the current page is the home page. If it is not and the user is not logged in, they are redirected to the login page.

Redirect to Login from a Specific Category

If you want to require login to view a specific category, you can use:

if ( is_category( 'my-category' ) && !is_user_logged_in() ) { 
    auth_redirect(); 
}

is_category( ‘my-category’ ) checks if the current page is in ‘my-category’. If it is and the user is not logged in, they are redirected to the login page.

Redirect to Login from a Specific Tag

To require login to view a specific tag, you can use:

if ( is_tag( 'my-tag' ) && !is_user_logged_in() ) { 
    auth_redirect(); 
}

In this example, is_tag( ‘my-tag’ ) checks if the current page has the tag ‘my-tag’. If it does and the user is not logged in, they are redirected to the login page.