Skip to content

Instantly share code, notes, and snippets.

@isGabe
Created June 21, 2013 16:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save isGabe/5832295 to your computer and use it in GitHub Desktop.
Save isGabe/5832295 to your computer and use it in GitHub Desktop.
WordPress: force log in to view any page, with redirect to requested URL#snippet #WordPress
<?php
/*
* Password protect a WordPress site, with a redirect to the requested URL after successful login
*
* Based on:
* http://wordpress.stackexchange.com/a/64999
* http://kovshenin.com/2012/current-url-in-wordpress/
*
**/
//Add this bit to your theme's functions.php or include in other appropriate place
add_action('template_redirect','fstop_check_if_logged_in');
function fstop_check_if_logged_in()
{
if(!is_user_logged_in()) //Are they logged in? If not:
{
// Get the requested URL
global $wp;
$requested_url = home_url( $wp->request );
//Set $url to {site_url()}/wp-login.php?redirect_to={$requested_url}
$url = add_query_arg(
'redirect_to',
$requested_url,
site_url('wp-login.php')
);
//redirect any request to {site_url()}/wp-login.php?redirect_to={$requested_url}
wp_redirect($url);
exit;
}
}
?>
@suntrop
Copy link

suntrop commented Dec 4, 2013

Thanks! Pretty exactly what I need :-)

@tommcg
Copy link

tommcg commented Dec 23, 2013

This works great in Chrome and Firefox..but IE 10+ generates a 302. I've been struggling with this for about a month. Thoughts?

@isGabe
Copy link
Author

isGabe commented Mar 19, 2014

@tommcg, just saw this comment. It looks like wp_redirect defaults to 302, but that is configurable with the $status argument.

@isGabe
Copy link
Author

isGabe commented Mar 19, 2014

I just tried to use this and got white scree. I found this method, which seems simpler and works:http://davidwalsh.name/wordpress-force-login

@sibaberpollo
Copy link

This is great !! One question, how to redirect to a different wp-login page?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment