The auth_redirect function in WordPress is used to protect certain pages or sections of a website from unauthorized access. It checks if a user is logged in and has the appropriate permissions to access a specific page. If the user is not logged in, they will be redirected to the login page or another page of your choice.
This function is particularly useful for websites that require users to log in to access certain content, such as membership sites, forums, or e-commerce stores. It can also be used to secure administration pages by preventing non-admin users from accessing them.
Here is an example usage code:
<?php
// Start the session
session_start();
// Redirect to login page if user is not logged in
if ( !is_user_logged_in() ) {
auth_redirect();
exit;
}
// Display the protected content here
?>
In this example, the auth_redirect function is used to redirect users who are not logged in to the login page. The is_user_logged_in function checks if the user is logged in, and if they are not, the auth_redirect function is called to redirect them to the login page. If the user is logged in, the protected content will be displayed.