プラグインに設定を追加して保存できるようにする
プラグインに設定項目(オプション)を追加するには以下のことを行う。
- メニューの作成
- 設定項目の登録
- 設定画面に表示するフォームを作成
<?php
/*
Plugin Name: Test plugin
Description: A test plugin to demonstrate wordpress functionality
Author: Test Name
Version: 0.1
*/
// プラグインに設定ページを追加
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu() {
// メニューの作成
add_menu_page(
__( 'TestPlugin', 'textdomain' ), // ページタイトル
'Test Plugin', // メニュータイトル
'manage_options', // Capabilities、メニューが含む機能?
'test-plugin', // メニューslug
'test_setting_function', // 設定画面で実行する関数
'dashicons-chart-pie' // メニューに表示するアイコン
);
// 設定の登録関数を呼び出し
add_action( 'admin_init', 'register_test_plugin_settings' );
}
// 設定の登録関数
function register_test_plugin_settings() {
// 設定項目を1つずつ追加、オプション名は取り出すときにも使う
register_setting( 'test-plugin-settings-group', 'test_option_1' );
register_setting( 'test-plugin-settings-group', 'test_option_2' );
register_setting( 'test-plugin-settings-group', 'test_option_3' );
}
// 設定画面で実行する関数
function test_setting_function() {
?>
<div class="wrap">
<h1>プラグイン名</h1>
<!-- 設定項目のフォーム -->
<form method="post" action="options.php">
<?php settings_fields( 'test-plugin-settings-group' ); ?>
<?php do_settings_sections( 'test-plugin-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">設定項目1</th>
<td><input type="text" name="test_option_1" value="<?php echo esc_attr( get_option('test_option_1') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">設定項目2</th>
<td><input type="text" name="test_option_2" value="<?php echo esc_attr( get_option('test_option_2') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">設定項目3</th>
<td><input type="text" name="test_option_3" value="<?php echo esc_attr( get_option('test_option_3') ); ?>" /></td>
</tr>
</table>
<!-- 保存ボタン -->
<?php submit_button(); ?>
</form>
</div>
<?php }
設定したデータをテンプレートに表示する方法
オプションをテンプレートで表示するには、get_option()
を使う。
パラメータには登録したオプション名を記入する。
<?php echo esc_attr( get_option('test_option_1') ); ?>