2026年5月20日
2026年5月20日
WordPressプラグインでオプションを保存する方法
はじめに
WordPressのOptions APIは add_option() / update_option() / get_option() でプラグイン設定をデータベースに保存する仕組みです。Settings APIと組み合わせることで管理画面の設定ページを安全に作成できます。
症状・原因
- プラグインの設定値をデータベースに保存したい
- 管理画面に設定ページを追加したい
- Settings APIでフォームのバリデーション・サニタイズを実装したい
- WP-CLIでプラグイン設定を確認・変更したい
解決手順
ステップ1:Options APIで設定を保存・取得する
// 設定を保存(初回のみ追加)
add_option('myplugin_settings', [
'api_key' => '',
'max_items' => 10,
'enabled' => true,
]);
// 設定を取得(デフォルト値付き)
$settings = get_option('myplugin_settings', [
'api_key' => '',
'max_items' => 10,
'enabled' => true,
]);
// 設定を更新(存在しない場合は追加)
update_option('myplugin_settings', [
'api_key' => 'new_key',
'max_items' => 20,
'enabled' => false,
]);
// 設定を削除
delete_option('myplugin_settings');
// autoload を無効化(大きなデータや頻繁に使わない設定)
add_option('myplugin_heavy_data', $data, '', 'no');
update_option('myplugin_heavy_data', $data, false);
ステップ2:Settings APIで設定ページを作成する
class Myplugin_Settings {
public function __construct() {
add_action('admin_menu', [$this, 'add_settings_page']);
add_action('admin_init', [$this, 'register_settings']);
}
public function add_settings_page(): void {
add_options_page(
'Myplugin 設定', // ページタイトル
'Myplugin', // メニュータイトル
'manage_options', // 必要な権限
'myplugin-settings', // スラッグ
[$this, 'render_page'] // コールバック
);
}
public function register_settings(): void {
register_setting(
'myplugin_options_group', // オプショングループ
'myplugin_settings', // オプション名
[
'sanitize_callback' => [$this, 'sanitize'],
'default' => ['api_key' => '', 'max_items' => 10],
]
);
add_settings_section(
'myplugin_main_section',
'基本設定',
null,
'myplugin-settings'
);
add_settings_field(
'myplugin_api_key',
'APIキー',
[$this, 'render_api_key_field'],
'myplugin-settings',
'myplugin_main_section'
);
add_settings_field(
'myplugin_max_items',
'最大表示件数',
[$this, 'render_max_items_field'],
'myplugin-settings',
'myplugin_main_section'
);
}
public function sanitize(array $input): array {
return [
'api_key' => sanitize_text_field($input['api_key'] ?? ''),
'max_items' => absint($input['max_items'] ?? 10),
];
}
public function render_api_key_field(): void {
$settings = get_option('myplugin_settings', []);
printf(
'<input type="text" name="myplugin_settings[api_key]" value="%s" class="regular-text">',
esc_attr($settings['api_key'] ?? '')
);
}
public function render_max_items_field(): void {
$settings = get_option('myplugin_settings', []);
printf(
'<input type="number" name="myplugin_settings[max_items]" value="%d" min="1" max="100">',
(int) ($settings['max_items'] ?? 10)
);
}
public function render_page(): void {
if (!current_user_can('manage_options')) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields('myplugin_options_group');
do_settings_sections('myplugin-settings');
submit_button('設定を保存');
?>
</form>
</div>
<?php
}
}
new Myplugin_Settings();
ステップ3:WP-CLIでオプションを管理する
# オプションを取得
wp option get myplugin_settings --format=json
# オプションを更新(JSON形式)
wp option update myplugin_settings '{"api_key":"new123","max_items":20}' --format=json
# オプションを削除
wp option delete myplugin_settings
# プラグイン関連のオプションをすべて確認
wp option list --search="myplugin*" --format=table
# autoloadされているオプションの容量確認
wp eval "
global \$wpdb;
\$size = \$wpdb->get_var(\"SELECT SUM(LENGTH(option_value))
FROM {\$wpdb->options} WHERE autoload='yes'\");
echo 'Autoload total: ' . size_format(\$size);
"
ステップ4:プラグイン有効化・無効化時の初期化処理
// 有効化時にデフォルト設定を追加
register_activation_hook(__FILE__, function(): void {
add_option('myplugin_settings', [
'api_key' => '',
'max_items' => 10,
'enabled' => true,
'version' => '1.0.0',
]);
});
// 削除時(uninstall.php)に設定を削除
// uninstall.php:
if (!defined('WP_UNINSTALL_PLUGIN')) {
exit;
}
delete_option('myplugin_settings');
delete_option('myplugin_heavy_data');
注意事項
get_option()の戻り値は保存時の型と異なる場合があります(シリアライズ→デシリアライズで文字列になることがある)。intキャストや型チェックを行ってください- autoload は
yes(デフォルト)にすると毎リクエストでロードされます。大きなデータはfalseに設定してください - Settings APIを使えばnonce・権限チェック・サニタイズが自動化されるため、直接フォーム処理するより安全です
まとめ
Options APIの update_option() でプラグイン設定を保存し、Settings APIと組み合わせることで管理画面の設定ページを安全に作れます。wp option get / update でWP-CLIから設定変更も可能です。