WP PHP

ページやカテゴリーにベーシック認証をかける

会員専用のコンテンツや、検索に拾われないページを作りたいときに使います。

準備

1)ベーシック認証を使用できるようにするための記述。

functions.php

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);
}

2)ベーシック認証をかけたいページを指定する。header.phpの先頭に記述。

固定ページの場合

<?php
if(!is_home()): 
if(is_page('2')): //Basic認証を掛けたいページID 
$userArray = array( "admin" => "password"
);
basic_auth($userArray); 
endif;
endif;
?>

カテゴリの場合

<?php
if(!is_home()): 
if(is_category('2')) :  //Basic認証を掛けたいカテゴリID
$userArray = array( "admin" => "password"
);
basic_auth($userArray); 
endif;
endif;
?>

投稿ページの場合

<?php
if(!is_home()): 
if(is_single('2')) :  //Basic認証を掛けたい投稿ID
$userArray = array( "admin" => "password"
);
basic_auth($userArray); 
endif;
endif;
?>

!)ユーザーIDやパスワードを入力しても弾かれる場合

.htaccessに記述

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

WordPressのパーマリンク設定の記述とは別に書くと吉。(WordPressの自動アップデートで上書きされない)

home > TIPS > WP PHP > ページやカテゴリーにベーシック認証をかける

Copyright © 2012 SMILEWORKS All Rights Reserved.