Skip to content

Instantly share code, notes, and snippets.

@fribibb
Forked from isGabe/wordpress-force-login.php
Created January 20, 2017 12:55
Show Gist options
  • Save fribibb/e088c1ad0470f7f0944ce0c0c13cb9c8 to your computer and use it in GitHub Desktop.
Save fribibb/e088c1ad0470f7f0944ce0c0c13cb9c8 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;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment