auth_redirect

Checks if a user is logged in, if not it redirects them to the login page.

Description

auth_redirect(); 

Usage

  1. if ( !function_exists( 'auth_redirect' ) ) { 
  2. require_once ABSPATH . WPINC . '/pluggable.php'; 
  3.  
  4.  
  5. // NOTICE! Understand what this does before running. 
  6. $result = auth_redirect(); 
  7.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/pluggable.php  
  1. function auth_redirect() { 
  2. // Checks if a user is logged in, if not redirects them to the login page 
  3.  
  4. $secure = ( is_ssl() || force_ssl_admin() ); 
  5.  
  6. /** 
  7. * Filter whether to use a secure authentication redirect. 
  8. * @since 3.1.0 
  9. * @param bool $secure Whether to use a secure authentication redirect. Default false. 
  10. */ 
  11. $secure = apply_filters( 'secure_auth_redirect', $secure ); 
  12.  
  13. // If https is required and request is http, redirect 
  14. if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { 
  15. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) { 
  16. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); 
  17. exit(); 
  18. } else { 
  19. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 
  20. exit(); 
  21.  
  22. if ( is_user_admin() ) { 
  23. $scheme = 'logged_in'; 
  24. } else { 
  25. /** 
  26. * Filter the authentication redirect scheme. 
  27. * @since 2.9.0 
  28. * @param string $scheme Authentication redirect scheme. Default empty. 
  29. */ 
  30.  
  31. if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) { 
  32. /** 
  33. * Fires before the authentication redirect. 
  34. * @since 2.8.0 
  35. * @param int $user_id User ID. 
  36. */ 
  37. do_action( 'auth_redirect', $user_id ); 
  38.  
  39. // If the user wants ssl but the session is not ssl, redirect. 
  40. if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { 
  41. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) { 
  42. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); 
  43. exit(); 
  44. } else { 
  45. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 
  46. exit(); 
  47.  
  48. return; // The cookie is good so we're done 
  49.  
  50. // The cookie is no good so force login 
  51.  
  52. $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); 
  53.  
  54. $login_url = wp_login_url($redirect, true); 
  55.  
  56. wp_redirect($login_url); 
  57. exit();