Wordpress Authentication Middleware
What I want to achieve is:
For every request , if the user is not logged he / she will be redirected to the log in page. If the user is logged in then he / she can access the site.
class Auth{
protected static $instance = null;
public function checkAuth(){
auth_redirect();
}
public static function getInstance() {
if (null == self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
}
Having this draft class what is the best action hook for this check? wp
, init
, template_redirect
?
Example of usage:
add_action('wp', array(Auth::getInstance(), 'checkAuth'));
UPDATE
I played a bit around with the hooks and I noticed that:
When I hook it to 'wp' or on 'template_redirect' then I get the log in page but every time I logged in it prompt me to log in again, and again and again.
When I hook it to 'init' I get a
Request-URI Too Long
The requested URL's length exceeds the capacity limit for this server.
The problem seems to be with auth_redirect() wordpress function.
I change my checkAuth function inside of Auth class with
if(!is_user_logged_in()) wp_safe_redirect(site_url('/wp-login.php'));
I test again the three hooks and now wp and template_redirect works fine but the init hook cause a redirect loop error.
Any ideas why is this happening ? (Refrence: Using `auth_redirect` : keeps asking me to login even when Im logged in)
Topic authorization authentication users Wordpress
Category Web