Menu
テーマ切り替え

ワードプレスの管理画面にオリジナルメニューとテキストフィールドを作成する

wordpress

ワードプレスの管理画面にオリジナルメニューを追加する方法になります。また、メニュー内にテキストフィールドとテキストエリアを作成し、保存、出力までの流れをご紹介します。

カスタム管理ページ用のプラグインファイルを作成

WordPressのテーマフォルダ内にある functions.php ファイルに、以下のコードを追加します。これにより、新しい管理ページが追加されます。

functions.php

add_action('admin_menu', 'my_custom_menu');

function my_custom_menu() {
  add_menu_page(
    'テーマ設定', // ページのタイトル
    'テーマ設定', // メニューのタイトル
    'manage_options', // 権限
    'custom-menu-slug', // スラッグ
    'my_custom_menu_page', // コールバック関数
    'dashicons-admin-generic', // アイコン
    '6', // メニューの位置
  );
}
function my_custom_menu_page() {
  ?>
  <div class="wrap">
    <h1>ここにカスタムメニューの内容を記入</h1>
    <form method="post" action="options.php">
      <?php
      settings_fields('my_custom_settings_group');
      do_settings_sections('my_custom_settings_group');
      ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row">サンプルオプション</th>
          <td><input type="text" name="my_sample_text_option" value="<?php echo esc_attr( get_option('my_text_option') ); ?>" /></td>
        </tr>
        <tr valign="top">
          <th scope="row">テキストエリア</th>
          <td><textarea name="my_sample_textarea_option" rows="10" cols="50"><?php echo esc_textarea( get_option('my_textarea_option') ); ?></textarea></td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>
  </div>
  <?php
}

入力した内容を登録

次に、入力した内容を登録するためのコードを functions.php に追加します。

functions.php

add_action('admin_init', 'my_custom_settings');

function my_custom_settings() {
  register_setting('my_custom_settings_group', 'my_text_option');
  register_setting('my_custom_settings_group', 'my_textarea_option');
}

テキストフィールドとテキストエリアのショートコードを作成

functions.php ファイルに以下のコードを追加します。

テキストフィールド

function display_sample_text_content_shortcode() {
  $sample_text_content = get_option('my_text_option');
  return '<div class="my-text-output">' . esc_html($sample_text_content) . '</div>';
}
add_shortcode('display_sample_text_content', 'display_sample_text_content_shortcode');

テキストエリア

function display_sample_textarea_content_shortcode() {
  $sample_textarea_content = get_option('my_textarea_option');
  return '<div class="my-textarea-output">' . $sample_textarea_content . '</div>';
}
add_shortcode('display_sample_textarea_content', 'display_sample_textarea_content_shortcode');

ショートコードを使用

任意のページや投稿に以下のショートコードを追加して、それぞれの内容を表示させます。

//テキストフィールド
[display_sample_text_content]
//テキストエリア
[display_sample_textarea_content]

テーマに追加して表示したい場合はこちら

//テキストフィールド
<?php echo do_shortcode('[display_sample_text_content]'); ?>
//テキストエリア
<?php echo do_shortcode('[display_sample_textarea_content]'); ?>

これで、テキストフィールドとテキストエリアの内容をショートコードで表示させることができます。

作成したテキストエリアなどでHTMLを許可したい場合はこちら

[blogcard url=“https://www.design.pon-poo.com/tutorial/post-1320/”\]

RU DESIGN
AUTHOR

RU DESIGN

個人開発者として、Webサイト制作やAIを活かした開発に取り組んでいます。このブログでは、私が実際に試して「これは使える!」と思った技術や、自作の便利ツールをシェアしています。一緒に技術を楽しんでいきましょう!

この記事をシェア:

関連記事