LoginSignup
3
6

More than 5 years have passed since last update.

WordPressでカテゴリーや固定ページなどでBasic認証

Posted at

functions.phpにBasic認証を掛けるための関数を記述

//ここから
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);
}
//.ここまで

header.phpの一番上で関数呼び出し

<?php
//Basic認証
if(!is_home()): 
if(is_tax('タクソノミーのスラッグ','タームのID、名前')): //Basic認証を掛けたいタクソノミー
if(is_category('カテゴリID')): //Basic認証を掛けたいカテゴリID
if(is_page('固定ページID')): //Basic認証を掛けたい固定ページID
if(get_post_type()=== '投稿タイプ名'): //Basic認証を掛けたい投稿タイプ名
//ID・パスワード配列
$userArray = array(
"basic" => "basic",
"test" => "test"
);
basic_auth($userArray); 
endif;
endif;
//.Basic認証
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6