wordpressの特定のページにBASIC認証をかける

wordpress

このページのworksのところにもかけてますが、要は特定の人にだけ見せたいようなページに対してBASIC認証をかける方法です。

まずはfunctions.phpに以下を追記。

//Basic認証
add_action( 'wp_head', 'password_post_header' );
function basic_auth($auth_list,$realm="Restricted Area",$failed_text="認証に失敗しました"){ 
    if (isset($_SERVER['PHP_AUTH_USER']) and isset($auth_list[$_SERVER['PHP_AUTH_USER']])){
        if ($auth_list[$_SERVER['PHP_AUTH_USER']] == $_SERVER['PHP_AUTH_PW']){
            return $_SERVER['PHP_AUTH_USER'];
        }
    }
 
    header('WWW-Authenticate: Basic realm="'.$realm.'"');
    header('HTTP/1.0 401 Unauthorized');
    header('Content-type: text/html; charset='.mb_internal_encoding());
 
    die($failed_text);
}

次にBASIC認証をかけたいページに以下を記入。
adminがユーザ名、passwordがパスワードにそれぞれ対応しているので、各々変更してください。

<div class="autherror">
	<?
		$userArray = array("admin" => "password"
		);
		basic_auth($userArray); 
	?>
</div>

質問やご指摘など気軽にどうぞ

コメントを投稿する

CAPTCHA