Skip to content

Instantly share code, notes, and snippets.

@retgef
Last active July 23, 2020 22:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save retgef/5b1dde806a64a84a746a to your computer and use it in GitHub Desktop.
Save retgef/5b1dde806a64a84a746a to your computer and use it in GitHub Desktop.
<?php
function send_http_auth_headers(){
header('WWW-Authenticate: Basic realm="Your Website Name Restricted"');
header('HTTP/1.0 401 Unauthorized');
echo 'Please speak to an administrator for access to the this feature.';
exit;
}
add_action('template_redirect', 'maybe_add_http_auth_basic', 0);
function maybe_add_http_auth_basic(){
# Add your specific URI segment (i.e. http://example.com/segment-string/)
$uri = 'segment-string';
if(!is_admin()){
global $wp;
# Look for exact match and child segments
if($wp->request === $uri || strpos($wp->request, $uri.'/') !== false ){
$user = HTTP_USER_NAME; # Define this in wp-config.php
$pass = HTTP_USER_PASS; # Define this in wp-config.php
# Check if user/pass has been entered
if (!isset($_SERVER['PHP_AUTH_USER'])) {
send_http_auth_headers();
} else{
# Check if the user/pass is correct
if ($_SERVER['PHP_AUTH_USER'] !== $user && $_SERVER['PHP_AUTH_PW'] !== $pass) {
send_http_auth_headers();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment