add_option_update_handler()
は、WordPress のオプションの更新時にカスタムのサニタイズ(データの適正化)処理を追加するための関数です。
しかし、この関数は WordPress 3.0.0 で非推奨(deprecated)になっており、現在は register_setting()
の使用が推奨されています。
register_setting()
を使用することで、管理画面の設定項目にバリデーションやサニタイズ処理を適用できるため、最新の WordPress ではそちらを利用するのがベストプラクティスです。
機能の説明
add_option_update_handler()
は、WordPress の設定オプションを登録し、その値のサニタイズ(適正化)処理を定義するための関数です。
例えば、管理画面の設定ページでユーザーが入力した値が正しい形式かどうかを確認し、不正なデータを防ぐのに役立ちます。
非推奨になった理由
この関数は WordPress 3.0.0 で _deprecated_function()
を使用して非推奨化 されており、register_setting()
を使用するよう推奨されています。
現在この関数を使用すると、WordPress のログに非推奨警告が出る 可能性があります。
シンプルなコード例
非推奨の方法(現在は推奨されていない)
add_option_update_handler('general', 'my_custom_option', 'sanitize_text_field');
'general'
グループの my_custom_option
に対して sanitize_text_field
を適用
推奨される方法
register_setting('general', 'my_custom_option', array(
'sanitize_callback' => 'sanitize_text_field',
));
'general'
グループの my_custom_option
に対してサニタイズ処理を設定
使い方の説明(register_setting()
)
基本的な使い方
register_setting()
を使ってオプションを登録し、適切なサニタイズ処理を適用する方法を紹介します。
function my_custom_settings() {
register_setting('general', 'my_custom_option', array(
'sanitize_callback' => 'my_custom_sanitize_function',
));
}
// サニタイズ関数(オプションの値を適正化)
function my_custom_sanitize_function($input) {
return sanitize_text_field($input); // テキストフィールドのサニタイズ
}
add_action('admin_init', 'my_custom_settings');
解説
register_setting('general', 'my_custom_option', array(...))
'general'
グループに'my_custom_option'
を登録sanitize_callback
を指定してデータを適正化
my_custom_sanitize_function($input)
- ユーザーが入力したデータを
sanitize_text_field()
でサニタイズ
一緒に使うことが多い関連タグ
update_option()
オプションの値を手動で更新するための関数です。
update_option('my_custom_option', 'new_value');
get_option()
オプションの値を取得するための関数です。
$value = get_option('my_custom_option', 'default_value');
register_setting()
オプションを登録し、バリデーションやサニタイズ処理を適用するための関数です。
register_setting('general', 'my_custom_option', array(
'sanitize_callback' => 'sanitize_text_field',
));
追加情報で取得したい場合
オプションのバリデーション
オプションの入力値を厳格にチェックしたい場合は、sanitize_callback
に独自の関数を指定できます。
function validate_custom_option($input) {
if (!is_numeric($input)) {
add_settings_error('my_custom_option', 'invalid_number', '数値を入力してください');
return get_option('my_custom_option'); // 元の値を維持
}
return $input;
}
register_setting('general', 'my_custom_option', array(
'sanitize_callback' => 'validate_custom_option',
));
想定されるトラブル
add_option_update_handler()
を使うと警告が出る
この関数は WordPress 3.0.0 で非推奨になっているため、使用するとエラーログに警告が表示される可能性があります。
解決方法
代わりに register_setting()
を使用する。
register_setting('general', 'my_custom_option', array(
'sanitize_callback' => 'sanitize_text_field',
));
Q&A
まとめ
add_option_update_handler()
はオプションのサニタイズ処理を設定する関数だったが、WordPress 3.0.0 で非推奨になった。- 代わりに
register_setting()
を使用することで、オプションのバリデーションやサニタイズを適用できる。 update_option()
やget_option()
と組み合わせて使うことで、オプション管理が容易になる。sanitize_callback
に適切な関数を指定することで、データの適正化が可能。
コメント