WP 特定のページにbasic認証をつける(カスタムフィールドでパスワードを設定)

ACFでオプションページの設定

functions.php にオプションページの記載をする

if( function_exists('acf_add_options_page') ) {
    acf_add_options_page(array(
        'page_title'    => 'テストオプションページ',
        'menu_title'    => 'テストオプションページ',
        'menu_slug'     => 'test-optionpage-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false
    ));
}

管理画面からカスタムフィールドの設定を行う。

Advanced Custom Fields のオプションページの設定方法と表示方法 | wp.geek

固定ページにBasic認証を設定

function.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
if (!is_home()) :
  if (get_post_type() === 'parent-post' || is_page('912') || is_singular('parent-post') || has_term('parent_cat') || is_post_type_archive('parent-post')) :
    $user = get_field('user', 'option');
    $pass = get_field('pass', 'option');
    $userArray = array(
      "$user" => "$pass"
    );
    basic_auth($userArray);
  endif;
endif;
?>

WordPress 固定ページにベーシック認証を設定する方法 - by Takumi Hirashima