Skip to content

Instantly share code, notes, and snippets.

@wpjess
Created June 17, 2021 22:02
Show Gist options
  • Save wpjess/5b15142eae2115da958eeb1a5ec7261b to your computer and use it in GitHub Desktop.
Save wpjess/5b15142eae2115da958eeb1a5ec7261b to your computer and use it in GitHub Desktop.
HTTP Auth for single WordPress page
function http_auth_headers(){
header('WWW-Authenticate: Basic realm="Web Page Restricted"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter the correct credentials to access this page';
exit;
}
add_action('template_redirect', 'add_http_auth_basic', 0);
function add_http_auth_basic(){
$uri = 'contact';
if(!is_admin()){
global $wp;
if($wp->request === $uri || strpos($wp->request, $uri.'/') !== false ){
$user = HTTP_USER_NAME;
$pass = HTTP_USER_PASS;
if (!isset($_SERVER['PHP_AUTH_USER'])) {
http_auth_headers();
} else{
if ($_SERVER['PHP_AUTH_USER'] !== $user && $_SERVER['PHP_AUTH_PW'] !== $pass) {
http_auth_headers();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment