LoginSignup
7
6

More than 5 years have passed since last update.

WordPress マルチサイト時のユーザ名制限解除

Posted at

背景

WordPressのマルチサイト機能をONにした際に、ユーザ名の登録制限がかかり、アルファベット小文字と数字のみのユーザ名しか設定できない。
ユーザ認証をActive Directory認証にしている事から、Active Directoryのユーザ名として利用している文字列は登録できるようにしたい。

概要

マルチサイトでのユーザ追加時の入力チェック関数 wpmu_validate_user_signup で発生するエラーに WordPressのフィルターフックを設定し、独自ルールにカスタマイズ

  • WordPress及びPluginの更新によりカスタマイズが消失しないように、既存ソースの変更は行わない

実装

プラグインフォルダの作成

WordPressディレクトリのwp-content 内にmu-plugins フォルダを作成
mkdir wp-content/mu-plugins && chmod 744 wp-content/mu-plugins

フィルターフック用のPHPファイルを作成する

mu-plugins に配置されたPHPファイルは自動的に適用される
vim wp-content/mu-plugins/multisite-userfilter.php

/wp-content/mu-plugins/multisite-userfilter.php
<?php
add_filter('wpmu_validate_user_signup', 'mywp_username_validation');

/* ユーザ名にハイフンを含める為のフィルター */
function mywp_username_validation($result){
    # ユーザ名で小文字+及び数字のみのエラーが発生している場合は エラーをリセット
    if (isset($result['errors']->errors['user_name']) && ($key = array_search(__('Usernames can only contain lowercase letters (a-z) and numbers.'), $result['errors']->errors['user_name'])) !== false) {
        unset($result['errors']->errors['user_name'][$key]);
        if (empty($result['errors']->errors['user_name'])) unset($result['errors']->errors['user_name']);

        # オリジナル条件でユーザ名をチェック
        # ここではアルファベット(大文字、小文字)、数字、記号(ハイフン、アンダースコア、アットマーク、ドット)を許可
        if ( $user_name != $orig_username || preg_match( '/[^A-Za-z0-9-_@\.]/', $user_name ) ) { 
            $errors->add( 'user_name', __( 'Usernames can only contain Alphabets (A-Z, a-z) and numbers, 4 special caracters (-,_,@,.)' ) );
            $user_name = $orig_username;
        }
    }   
}

?>

Active Directoryのユーザ名として一般的に利用しているハイフンだけでもOKでしたが、今後の拡張を考えて、他の記号も追加してみました。

参考ページ

7
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
7
6