Cocoon設定画面に独自タブを追加する方法(Cocoon 2.9.5.1~)

Cocoonカスタマイズ集
この記事は約8分で読めます。
記事内に広告が含まれています。

はじめに

以前の記事では、JavaScript(DOM操作)を用いて Cocoon 設定画面に独自タブを追加する方法をご紹介しました。

前回のJavaScript方式でも動的にタブを拡張できましたが、Cocoon 2.9.5.1から「Cocoon設定にタブ拡張フック」が追加されました。

以下の公式フックを利用することで、JavaScriptを一切使わず、PHPのみで独自タブを追加できる仕組みが整いました。

  • cocoon_settings_tabs(設定タブの追加・定義)
  • cocoon_settings_tab_content_{$tab_id}(タブ内のコンテンツ出力)

この記事では、この方法について説明します。

目的

JavaScript方式からCocoon 2.9.5.1で導入されたフック方式へ移行することで、主に2つのメリットがあります。

  1. 画面のチラつきを防止し、パフォーマンスが向上する
    ページの読み込み完了(DOM操作)を待たずにサーバー側で即座にタブが生成されるため、レンダリング時の表示遅延やチラつきが発生しません。
  1. コードの記述量を削減し、メンテナンス性を高められる
    タブの切り替え状態(ラジオボタンのchecked判定など)をCocoon本体のロジックに任せられるため、コード量を大幅に削減できます。
    さらに、テーマのバージョンアップ等でDOM構造が変わっても影響を受けにくく動作が安定します。

実装手順

事前準備:設定値の定義と保存処理

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

設定の保存には Cocoon 拡張用の保存フック cocoon_settings_save_{$tab_id}を使用します。

/**
 * オプション設定を管理
 *
 * @return array オプション設定の配列
 */
if (!function_exists('my_cocoon_options')):
function my_cocoon_options() {
  return [
    'my_custom_message'             => ['default' => '', 'label' => 'メッセージ'],
    'my_custom_phone'               => ['default' => '', 'label' => '電話番号'],
    'my_custom_business_hours'      => ['default' => '', 'label' => '営業時間'],
    'my_custom_button_text'         => ['default' => '', 'label' => '問い合わせボタンのテキスト'],
    'my_custom_button_url'          => ['default' => '', 'label' => '問い合わせリンクURL'],
    'my_custom_request_button_text' => ['default' => '', 'label' => '資料請求ボタンのテキスト'],
    'my_custom_request_button_url'  => ['default' => '', 'label' => '資料請求リンクURL'],
  ];
}
endif;


/**
 * オプション設定値を取得
 *
 * @param string $key オプションキー名
 * @return mixed 設定された値(未設定の場合はデフォルト値)
 */
if (!function_exists('get_my_cocoon_options')):
function get_my_cocoon_options($key) {
  $options = my_cocoon_options();

  return get_theme_option($key, $options[$key]['default']);
}
endif;


// 独自タブ(custom-header)のデータを保存
add_action('cocoon_settings_save_custom-header', function () {
  foreach (array_keys(my_cocoon_options()) as $key) {
    update_theme_option($key);
  }
});

functions.phpのみで完結させる場合

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

フックcocoon_settings_tabsでタブを定義し、cocoon_settings_tab_content_custom-headerでフォームを出力します。

// Cocoon設定に独自タブを追加
add_filter('cocoon_settings_tabs', function ($definitions) {
  $definitions['custom-header'] = [
    'label' => 'カスタムヘッダー',
  ];

  return $definitions;
});


// 独自タブ内のコンテンツを出力
add_action('cocoon_settings_tab_content_custom-header', function () {
  ?>
  <div class="metabox-holder">
    <div id="custom-header-settings" class="postbox">
      <h2 class="hndle"><span>カスタムヘッダー設定</span></h2>
      <div class="inside">
        <table class="form-table">
          <tbody>
            <?php foreach (my_cocoon_options() as $key => $option): ?>
              <?php $value = esc_attr(get_my_cocoon_options($key)); ?>
              <tr>
                <th scope="row">
                  <label for="<?php echo esc_attr($key); ?>"><?php echo esc_html($option['label']); ?></label>
                </th>
                <td>
                  <input type="text" id="<?php echo esc_attr($key); ?>" name="<?php echo esc_attr($key); ?>" value="<?php echo $value; ?>" class="regular-text">
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <?php
});

設定画面を外部ファイルに切り出す場合

以下の手順で実装します。

  • ラベル
    PHPを追加

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

    // Cocoon設定に独自タブを追加
    add_filter('cocoon_settings_tabs', function ($definitions) {
      $definitions['custom-header'] = [
        'label' => 'カスタムヘッダー',
      ];
    
      return $definitions;
    });
    
    
    // 独自タブのコンテンツを出力
    add_action('cocoon_settings_tab_content_custom-header', function () {
      $file_path = get_stylesheet_directory() . '/tab/my-header-tab.php';
    
      if (file_exists($file_path)) {
        require $file_path;
      }
    });
  • ラベル
    PHPを追加

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

    ファイルパス: cocoon-child-master/tab/my-header-tab.php

    <?php
    if (!defined('ABSPATH')) {
      exit;
    }
    
    ?>
    <div class="metabox-holder">
      <div id="custom-header-settings" class="postbox">
        <h2 class="hndle"><span>カスタムヘッダー設定</span></h2>
        <div class="inside">
          <table class="form-table">
            <tbody>
              <?php foreach (my_cocoon_options() as $key => $option): ?>
                <?php $value = esc_attr(get_my_cocoon_options($key)); ?>
                <tr>
                  <th scope="row">
                    <label for="<?php echo esc_attr($key); ?>">
                      <?php echo esc_html($option['label']); ?>
                    </label>
                  </th>
                  <td>
                    <input type="text" id="<?php echo esc_attr($key); ?>" name="<?php echo esc_attr($key); ?>" value="<?php echo $value; ?>" class="regular-text">
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

まとめ

今回紹介した方法を使えば、JavaScript を一切使うことなく、PHPのみでCocoon設定画面に独自タブを追加できます。
テーマのバージョンアップによる影響を受けにくい点や、動作のチラつきがない点など、多くのメリットがあります。

タイトルとURLをコピーしました